We can use the Object.getOwnPropertyNames()
function to get all the property names linked to an object.
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.
For example here is how we might create a utility function to do what we need:
getMethods = (obj) => Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function')
This lists only the methods defined on that specific object, not any method defined in its prototype chain.
To do that we must take a slightly different route. We must first iterate the prototype chain and we list all the properties in an array. Then we check if each single property is a function.
An easy way to make sure we don’t duplicate methods as we navigate the prototype chain (like constructor
which is always present), we use a Set 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')
}
Example usage:
getMethods("")
getMethods(new String('test'))
getMethods({})
getMethods(Date.prototype)
Download my free JavaScript Beginner's Handbook and check out my JavaScript Course!
More js tutorials:
- How to remove a property from a JavaScript object
- How to get tomorrow's date using JavaScript
- JavaScript Return Values
- How to return multiple values from a function in JavaScript
- JavaScript Proxy Objects
- The Object keys() method
- This decade in JavaScript
- The Object isSealed() method
- The JavaScript for..of loop