Get all methods of any object JavaScript


We are required to write a program (function) that takes in an object reference and returns an array of all the methods (member functions) that lives on that object.We are only required to return the methods in the array and not any other property that might have value of type other than a function.

We will use the Object.getOwnPropertyNames function

The Object.getOwnPropertyNames() method returns an array of all properties (enumerable or not) found directly upon a given object. And then we will filter the array to contain property of data type 'function' only.

Example

const returnMethods = (obj = {}) => {
   const members = Object.getOwnPropertyNames(obj);
   const methods = members.filter(el => {
      return typeof obj[el] === 'function';
   })
   return methods;
};
console.log(returnMethods(Array.prototype));

Output

And the output in the console will be −

[
   'constructor', 'concat', 'copyWithin',
'fill', 'find', 'findIndex', 'lastIndexOf', 'pop', 'push',
   'reverse', 'shift', 'unshift', 'slice', 'sort', 'splice',
   'includes', 'indexOf', 'join',
   'keys', 'entries', 'values',
   'forEach', 'filter', 'flat',
   'flatMap', 'map', 'every',
   'some', 'reduce', 'reduceRight',
   'toLocaleString', 'toString'
]

Updated on: 21-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements