Learn how to obtain an array containing all the methods of a JavaScript object.

To accomplish this, we can utilize the Object.getOwnPropertyNames() function. This function allows us to retrieve all the property names associated with an object.

Once we have the resulting array, we can filter it to only include property names that represent functions. To determine if a property is a function, we can use the typeof operator.

Here’s an example of how we can create a utility function to achieve our goal:

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

This function will only list the methods that are defined directly on the object, excluding any methods defined in its prototype chain.

If we want to include methods from the prototype chain as well, we need to take a slightly different approach. In this case, we need to iterate through the prototype chain and gather all the properties into an array. Then, we can check if each property is a function.

To prevent duplicating methods as we traverse the prototype chain (such as the constructor method, which is always present), we can use a Set data structure. The Set ensures that the 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')
}

Here’s an example of how to use this function:

getMethods("") 
getMethods(new String('test'))
getMethods({})
getMethods(Date.prototype)

Tags: JavaScript, Object methods, Prototype chain, Utility function, Set