JavaScript中获取对象的所有函数
例如,
Math.mymfunc = function (x) {
return x+1;
}
将被视为属性,当我编写时
for(var p in Math.__proto__) console.log(p)
它将显示。但其余的数学函数不会。如何获取 Math 对象的所有函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Object.getOwnPropertyNames(Math);
就是您所追求的。如果您正在使用兼容 EcmaScript 5 的浏览器,这会记录所有属性。
Object.getOwnPropertyNames(Math);
is what you are after.This logs all of the properties provided you are dealing with an EcmaScript 5 compliant browser.
这为您提供了函数属性名称的数组。接受的答案为您提供了所有属性的名称。
That gives you an array of the names of the properties that are functions. Accepted answer gave you names of all the properties.
规范似乎没有定义
Math 的属性
函数定义为。大多数实现似乎都将 DontEnum 应用于这些函数,这意味着当使用 for(i in Math) 循环进行迭代时,它们不会出现在对象中。请问您需要这样做的目的是什么?函数并不多,因此最好在数组中自己定义它们:
The specification doesn't appear to define with what properties the
Math
functions are defined with. Most implementations, it seems, applyDontEnum
to these functions, which mean they won't show up in the object when iterated through with afor(i in Math)
loop.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:
console.log(Math)
应该可以工作。console.log(Math)
should work.Object.getOwnPropertyNames() 是一个好的解决方案
下面的示例是如果您已经编写了一个示例脚本并希望为每个功能创建一个按钮。
Object.getOwnPropertyNames() is a good solution
The following example is if you have written a sample script and want to create a button for each function.