[javascript] How to get an object's methods?

Is there a method or propertie to get all methods from an object? For example:

function foo() {}
foo.prototype.a = function() {}
foo.prototype.b = function() {}

foo.get_methods(); // returns ['a', 'b'];

UPDATE: Are there any method like that in Jquery?

Thank you.

This question is related to javascript function object methods get

The answer is


In ES6:

let myObj   = {myFn : function() {}, tamato: true};
let allKeys = Object.keys(myObj);
let fnKeys  = allKeys.filter(key => typeof myObj[key] == 'function');
console.log(fnKeys);
// output: ["myFn"]

var funcs = []
for(var name in myObject) {
    if(typeof myObject[name] === 'function') {
        funcs.push(name)
    }
}

I'm on a phone with no semi colons :) but that is the general idea.


Remember that technically javascript objects don't have methods. They have properties, some of which may be function objects. That means that you can enumerate the methods in an object just like you can enumerate the properties. This (or something close to this) should work:

var bar
for (bar in foo)
{
    console.log("Foo has property " + bar);
}

There are complications to this because some properties of objects aren't enumerable so you won't be able to find every function on the object.


In Chrome is keys(foo.prototype). Returns ["a", "b"].

See: https://developer.chrome.com/devtools/docs/commandline-api#keysobjectenter image description here

Later edit: If you need to copy it quick (for bigger objects), do copy(keys(foo.prototype)) and you will have it in the clipboard.


In modern browsers you can use Object.getOwnPropertyNames to get all properties (both enumerable and non-enumerable) on an object. For instance:

function Person ( age, name ) {
    this.age = age;
    this.name = name;
}

Person.prototype.greet = function () {
    return "My name is " + this.name;
};

Person.prototype.age = function () {
    this.age = this.age + 1;
};

// ["constructor", "greet", "age"]
Object.getOwnPropertyNames( Person.prototype );

Note that this only retrieves own-properties, so it will not return properties found elsewhere on the prototype chain. That, however, doesn't appear to be your request so I will assume this approach is sufficient.

If you would only like to see enumerable properties, you can instead use Object.keys. This would return the same collection, minus the non-enumerable constructor property.


You can use console.dir(object) to write that objects properties to the console.


The methods can be inspected in the prototype chain of the object using the browser's developer tools (F12):

  console.log(yourJSObject);

or more directly

  console.dir(yourJSObject.__proto__);

the best way is:

let methods = Object.getOwnPropertyNames(yourobject);
console.log(methods)

use 'let' only in es6, use 'var' instead


var methods = [];
for (var key in foo.prototype) {
    if (typeof foo.prototype[key] === "function") {
         methods.push(key);
    }
}

You can simply loop over the prototype of a constructor and extract all methods.


for me, the only reliable way to get the methods of the final extending class, was to do like this:

function getMethodsOf(obj){
  const methods = {}
  Object.getOwnPropertyNames( Object.getPrototypeOf(obj) ).forEach(methodName => {
    methods[methodName] = obj[methodName]
  })
  return methods
}

function getMethods(obj)
{
    var res = [];
    for(var m in obj) {
        if(typeof obj[m] == "function") {
            res.push(m)
        }
    }
    return res;
}

Get the Method Names:

var getMethodNames = function (obj) {
    return (Object.getOwnPropertyNames(obj).filter(function (key) {
        return obj[key] && (typeof obj[key] === "function");
    }));
};

Or, Get the Methods:

var getMethods     = function (obj) {
    return (Object.getOwnPropertyNames(obj).filter(function (key) {
        return obj[key] && (typeof obj[key] === "function");
    })).map(function (key) {
        return obj[key];
    });
};

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?