How to get an object's methods?

前端 未结 12 1140
暗喜
暗喜 2020-12-13 03:33

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()         


        
相关标签:
12条回答
  • 2020-12-13 03:51
    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.

    0 讨论(0)
  • 2020-12-13 03:54

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

    See: https://developer.chrome.com/devtools/docs/commandline-api#keysobject

    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.

    0 讨论(0)
  • 2020-12-13 03:56

    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.

    0 讨论(0)
  • 2020-12-13 03:58
    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.

    0 讨论(0)
  • 2020-12-13 03:59
    function getMethods(obj)
    {
        var res = [];
        for(var m in obj) {
            if(typeof obj[m] == "function") {
                res.push(m)
            }
        }
        return res;
    }
    
    0 讨论(0)
  • 2020-12-13 04:00

    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.

    0 讨论(0)
提交回复
热议问题