如何列出 javascript 对象的函数/方法?(这甚至可能吗?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4352997/
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
How to list the functions/methods of a javascript object? (Is it even possible?)
提问by BenoitParis
This question is intentionally phrased like this question.
这个问题是故意措辞像 这个问题。
I don't even know if this is possible, I remember vaguely hearing something about some properties not enumerable in JS.
我什至不知道这是否可能,我记得依稀听到一些在 JS 中无法枚举的属性。
Anyway, to cut a long story short: I'm developing something on a js framework for which I have no documentation and no easy access to the code, and it would greatly help to know what I can do with my objects.
无论如何,长话短说:我正在一个 js 框架上开发一些东西,我没有文档,也无法轻松访问代码,这将极大地帮助我了解我可以用我的对象做什么。
回答by Allan Tokuda
If you include Underscore.jsin your project, you can use _.functions(yourObject)
.
如果在项目中包含Underscore.js,则可以使用_.functions(yourObject)
.
回答by Mike Glenn
I think this is what you are looking for:
我认为这就是你要找的:
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
}
}
回答by andrewmu
You should be able to enumerate methods that are set directly on an object, e.g.:
您应该能够枚举直接在对象上设置的方法,例如:
var obj = { locaMethod: function() { alert("hello"); } };
But most methods will belong to the object's prototype, like so:
但是大多数方法都属于对象的原型,如下所示:
var Obj = function ObjClass() {};
Obj.prototype.inheritedMethod = function() { alert("hello"); };
var obj = new Obj();
So in that case you could discover the inherited methods by enumerating the properties of Obj.prototype.
因此,在这种情况下,您可以通过枚举 Obj.prototype 的属性来发现继承的方法。
回答by Giuseppe Romagnuolo
You can use the following:
您可以使用以下内容:
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.
}