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 15:58

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.

查看更多
放我归山
3楼-- · 2019-01-21 15:58
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.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-21 16:00

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
}
查看更多
不美不萌又怎样
5楼-- · 2019-01-21 16:05

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];
    });
};
查看更多
We Are One
6楼-- · 2019-01-21 16:12

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"]
查看更多
干净又极端
7楼-- · 2019-01-21 16:14

the best way is:

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

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

查看更多
登录 后发表回答