Javascript 如何获取对象的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5842654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:09:47  来源:igfitidea点击:

How to get an object's methods?

javascriptfunctionobjectmethodsget

提问by thom

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?

更新:Jquery 中是否有类似的方法?

Thank you.

谢谢你。

回答by Makram Saleh

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

回答by ReinstateMonica Larry Osterman

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:

请记住,从技术上讲,javascript 对象没有方法。它们具有属性,其中一些可能是函数对象。这意味着您可以像枚举属性一样枚举对象中的方法。这个(或接近这个)应该有效:

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 everyfunction on the object.

这样做很复杂,因为对象的某些属性是不可枚举的,因此您将无法找到对象上的每个函数。

回答by pstenstrm

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

您可以使用console.dir(object)将该对象的属性写入控制台。

回答by Sampson

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

在现代浏览器中,您可以使用Object.getOwnPropertyNames获取对象的所有属性(可枚举和不可枚举)。例如:

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.

请注意,这只会检索own-properties,因此它不会返回在原型链上的其他地方找到的属性。但是,这似乎不是您的要求,因此我认为这种方法就足够了。

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

如果您只想查看可枚举的属性,则可以改用Object.keys. 这将返回相同的集合,减去不可枚举的constructor属性。

回答by Matoeil

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

可以使用浏览器的开发人员工具 (F12) 在对象的原型链中检查这些方法:

  console.log(yourJSObject);

or more directly

或更直接

  console.dir(yourJSObject.__proto__);

回答by Kevin Beal

In ES6:

在 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"]

回答by Jo-Go

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
}

回答by Matt Greer

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.

我正在使用没有分号的电话 :) 但这是总体思路。

回答by Raynos

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.

您可以简单地遍历构造函数的原型并提取所有方法。

回答by Arturo Morales Rangel

the best way is:

最好的方法是:

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

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

仅在 es6 中使用 'let',改为使用 'var'