How to list all methods of an object in JavaScript

Learn how to use JavaScript object methods to get arrays

We can useObject.getOwnPropertyNames()Function to get all the attribute names linked to the object.

Then, we can filter the result array to include only the attribute name (if it is a function).

We determine whether it is a function by usingtypeofOn top.

For example, this is how we might create utility functions to perform the desired operations:

getMethods = (obj) => Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function')

This only lists the methods defined on that particular object, not any methods defined in its prototype chain.

For this, we must take a slightly different approach. We must first iterate the prototype chain, and then list all the properties in the array. Then, we check whether each attribute is a function.

A simple way to ensure that the method is not repeated when browsing the prototype chain (e.g.constructorAlways exists), we use the Set data structure to ensure that the value is 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 [].filter(item => typeof obj[item] === 'function')

Example usage:

getMethods(new String('test'))

Download mine for freeJavaScript beginner's manual

More js tutorials: