How to get an object's methods?

2019-01-21 15:57发布

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.

12条回答
该账号已被封号
2楼-- · 2019-01-21 16:16
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.

查看更多
Rolldiameter
3楼-- · 2019-01-21 16:18

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.

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-21 16:20
function getMethods(obj)
{
    var res = [];
    for(var m in obj) {
        if(typeof obj[m] == "function") {
            res.push(m)
        }
    }
    return res;
}
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-21 16:20

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

查看更多
▲ chillily
6楼-- · 2019-01-21 16:20

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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-21 16:24

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__);
查看更多
登录 后发表回答