How to list all methods of an object in JavaScript
By Flavio Copes
Learn how to list the methods of a JavaScript object with Object.getOwnPropertyNames() filtered by typeof, plus how to walk the prototype chain with a Set.
To list the methods of an object, get its property names with Object.getOwnPropertyNames() and keep the ones whose value is a function. To also include inherited methods, walk the prototype chain and repeat the check at each level.
Let’s start with the first case.
Listing the object’s own methods
Object.getOwnPropertyNames() gives us all the property names defined directly on an object, including non-enumerable ones that Object.keys() would skip.
Then we can filter the resulting array, to only include that property name if it’s a function. We determine if it’s a function by using typeof on it.
Here is a utility function that does this:
const getMethods = (obj) => Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function')
Let’s try it on an object literal:
const car = {
brand: 'Ford',
start() {},
stop() {}
}
getMethods(car) //['start', 'stop']
The brand property is filtered out because it’s a string, not a function.
What about inherited methods?
This lists only the methods defined on that specific object, not any method defined in its prototype chain.
You notice this immediately with class instances. Class methods live on the prototype, not on the instance, so the function above returns an empty array:
class Dog {
bark() {}
}
getMethods(new Dog()) //[]
To fix this we must take a slightly different route. We first iterate the prototype chain, and at each level we collect all the property names. Then we check if each single property is a function.
As we navigate the chain, some names show up more than once (like constructor, which is present at every level). To avoid duplicates we collect the names in a Set, a data structure that makes sure values are unique:
const getMethods = (obj) => {
let properties = new Set()
let currentObj = obj
do {
Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
} while ((currentObj = Object.getPrototypeOf(currentObj)))
return [...properties.keys()].filter(item => typeof obj[item] === 'function')
}
The do...while loop keeps calling Object.getPrototypeOf() until it returns null, at the end of the chain.
Now the Dog instance reports its methods, plus everything inherited from Object.prototype:
getMethods(new Dog())
//['constructor', 'bark', '__defineGetter__', ...]
Example usage on built-in objects:
getMethods('') //all the String methods
getMethods(new Date()) //all the Date methods
getMethods({}) //the Object.prototype methods
Which version you want depends on the question you’re asking. Use the first one to see what an object defines itself. Use the second one to see everything you can actually call on it.