How to get an object's methods?

前端 未结 12 1139
暗喜
暗喜 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:42

    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"]
    
    0 讨论(0)
  • 2020-12-13 03:44

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

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

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

    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];
        });
    };
    
    0 讨论(0)
  • 2020-12-13 03:47

    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__);
    
    0 讨论(0)
  • 2020-12-13 03:47

    the best way is:

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

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

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