给定一个任意的javascript对象,如何找到它的方法?
我知道这在python中是可能的,但是我可以获得javascript对象的方法列表吗?您可以循环对象中的属性并测试它们的类型给定一个任意的javascript对象,如何找到它的方法?,javascript,reflection,Javascript,Reflection,我知道这在python中是可能的,但是我可以获得javascript对象的方法列表吗?您可以循环对象中的属性并测试它们的类型 for(var prop in whatever) { if(typeof whatever[prop] == 'function') { //do something } } 要添加到现有答案中,ECMAScript第五版提供了一种使用方法object.getOwnPropertyNames访问对象的所有属性(即使是不可枚举的属性)的方
for(var prop in whatever) {
if(typeof whatever[prop] == 'function') {
//do something
}
}
要添加到现有答案中,ECMAScript第五版提供了一种使用方法
object.getOwnPropertyNames
访问对象的所有属性(即使是不可枚举的属性)的方法。当尝试枚举本机对象的属性时,例如Math
,afor..in
for(var property in Math) {
console.log(property);
}
将不会在控制台上打印任何内容。但是,
Object.getOwnPropertyNames(Math)
将返回:
["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "abc", "LN2", "cos", "pow", "log", "tan", "sqrt", "ceil", "asin", "abs", "max", "exp", "atan2", "random", "round", "floor", "acos", "atan", "min", "sin"]
您可以在此基础上编写一个helper函数,该函数只返回给定对象的方法
function getMethods(object) {
var properties = Object.getOwnPropertyNames(object);
var methods = properties.filter(function(property) {
return typeof object[property] == 'function';
});
return methods;
}
> getMethods(Math)
["cos", "pow", "log", "tan", "sqrt", "ceil", "asin", "abs", "max", "exp", "atan2", "random", "round", "floor", "acos", "atan", "min", "sin"]
目前对ECMAScript第五版的支持有点暗淡,因为只有Chrome、IE9pre3和Safari/Firefox nightlies支持它。此函数接收任意对象并返回其原型的名称、包含所有方法的列表以及包含其属性(及其类型)名称的对象。我没有机会在浏览器中测试它,但它可以与Nodejs(v0.10.24)一起使用 示例(使用Nodejs): 输出:
{ ClassName: 'RegExp',
Methods: [ 'constructor', 'exec', 'test', 'toString', 'compile' ],
Attributes:
{ source: 'string',
global: 'boolean',
ignoreCase: 'boolean',
multiline: 'boolean',
lastIndex: 'number' } }
以下示例也适用于NodeJ:
console.log(inspectClass(new RegExp("hello")));
console.log(inspectClass(RegExp));
console.log(inspectClass("hello"));
console.log(inspectClass(5));
console.log(inspectClass(undefined));
console.log(inspectClass(NaN));
console.log(inspectClass(inspectClass));
单线解决方案
Object.getOwnPropertyNames(JSON).filter(function(name){ return 'function' === typeof JSON[name]; })
['parse','stringify']
['fromCharCode','fromCodePoint','raw']
['isArray','from','of']
+我看不出有任何理由投反对票。顺便说一句,IE9pre3也支持它。谢谢@CMS,很高兴看到IE在v9上的表现。更新答案。是的,我真的很高兴看到IE9进展顺利,我只发现了一些关于属性描述符和
对象的bug(8+)。创建,希望这个周末我有时间报告它们。:)不可以。所有本机JavaScript函数都可以接受任意数量的参数。@在实现toSource、firefox的浏览器中,您现在只能使用func.toSource().match(/\([^\(\)]+\)/)[1]
。但这在内置函数上不起作用。
Object.getOwnPropertyNames(JSON).filter(function(name){ return 'function' === typeof JSON[name]; })
Object.getOwnPropertyNames(String).filter(function(name){ return 'function' === typeof String[name]; })
Object.getOwnPropertyNames(Array).filter(function(name){ return 'function' === typeof Array[name]; })