在 JavaScript 中获取对象的所有功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7548291/
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
Get all functions of an object in JavaScript
提问by Andr
For example,
例如,
Math.mymfunc = function (x) {
return x+1;
}
will be treated as a property and when I write
将被视为财产,当我写
for(var p in Math.__proto__) console.log(p)
it will be shown. But the rest of Math functions will not. How can I get all functions of a Math object?
它将被显示。但其余的数学函数不会。如何获得 Math 对象的所有函数?
回答by Lime
Object.getOwnPropertyNames(Math);
is what you are after.
Object.getOwnPropertyNames(Math);
是你所追求的。
This logs all of the properties provided you are dealing with an EcmaScript 5 compliant browser.
如果您正在处理兼容 EcmaScript 5 的浏览器,这会记录所有属性。
var objs = Object.getOwnPropertyNames(Math);
for(var i in objs ){
console.log(objs[i]);
}
回答by hylaea
var functionNames = [];
Object.getOwnPropertyNames(obj).forEach(function(property) {
if(typeof obj[property] === 'function') {
functionNames.push(property);
}
});
console.log(functionNames);
That gives you an array of the names of the properties that are functions. Accepted answer gave you names of all the properties.
这为您提供了作为函数的属性名称的数组。接受的答案为您提供了所有属性的名称。
回答by James
The specificationdoesn't appear to define with what properties the Math
functions are defined with. Most implementations, it seems, apply DontEnum
to these functions, which mean they won't show up in the object when iterated through with a for(i in Math)
loop.
该规范似乎没有定义Math
函数定义的属性。大多数实现似乎都适用DontEnum
于这些函数,这意味着它们在for(i in Math)
循环迭代时不会出现在对象中。
May I ask what you need to do this for? There aren't many functions, so it may be best to simply define them yourself in an array:
请问你需要这样做是为了什么?函数并不多,因此最好自己在数组中定义它们:
var methods = ['abs', 'max', 'min', ...etc.];
回答by Jason Barry
console.log(Math)
should work.
console.log(Math)
应该管用。