There are often times when you want to list all the methods of an object, but unfortunately such a feature does not seem to be built into Javascript at this time, and you must implement it yourself (as of February 24, 2024).
This article describes how to get all the methods of an object in Javascript.
Table of Contents
Code to get all the methods of an object
Here is the code to get the list of methods of an object as an array.
The do-while statement gets the list of properties including those from the parents, and finally the filter method returns only the methods excluding the constructor.
const getMethods = ( o, target = o, props = [] ) => {
do {
Reflect.ownKeys( o ).map(item => props.push(item))
} while( (o = Object.getPrototypeOf( o )) && o != Object.prototype )
return props.filter(p => typeof target[p] == 'function' && p != 'constructor')
}
How to use getMethods
Usage is simple: simply execute the getMethods method defined earlier with the object as an argument.
It can also be used for class instances and standard built-in objects.
getMethods({sampleMethod(){}}) // can be used for objects
getMethods(new SampleClass()) // can be used for class instances
getMethods(document) // can be used for standard built-in objects
Specifications for getMethods
The specification of getMethods which is implemented this time is as follows.
・All methods, including parents methods, are returned as an array.
・Methods of the “Object.prototype” are not included (because all objects have them in common).
・Constructors are excluded.
・Getter/setter are excluded.
That is all, it was about how to get all methods of an object in javascript.