如何列出javascript对象的函数/方法? (它甚至可能吗?)

时间:2010-12-04 10:02:13

标签: javascript methods scope member-functions

这个问题的用法有点像this question

我甚至不知道这是否可能,我记得有些人听到一些关于JS中无法枚举的属性的东西。

无论如何,简而言之:我正在js框架上开发一些东西,我没有文档,也没有简单的代码访问权限,这将非常有助于知道我可以用我的对象做什么。

4 个答案:

答案 0 :(得分:15)

如果您在项目中加入Underscore.js,则可以使用_.functions(yourObject)

答案 1 :(得分:11)

我认为这就是你要找的东西:

var obj = { locaMethod: function() { alert("hello"); }, a: "b", c: 2 };
for(var p in obj)
{
    if(typeof obj[p] === "function") {
      // its a function if you get here
    }
}

答案 2 :(得分:3)

您应该能够枚举直接在对象上设置的方法,例如:

var obj = { locaMethod: function() { alert("hello"); } };

但是大多数方法都属于对象的原型,如下所示:

var Obj = function ObjClass() {};
Obj.prototype.inheritedMethod = function() { alert("hello"); };
var obj = new Obj();

因此,在这种情况下,您可以通过枚举Obj.prototype的属性来发现继承的方法。

答案 3 :(得分:1)

您可以使用以下内容:

var obj = { locaMethod: function() { alert("hello"); }, a: "b", c: 2 };


for(var p in obj)
{
    console.log(p + ": " + obj[p]); //if you have installed Firebug.
}
相关问题