[英]Is it possible to iterate over the static variables and methods of a class with CoffeeScript?
Using CoffeeScript, I would like to be able to iterate over the static methods and variables of a class. 使用CoffeeScript,我希望能够遍历类的静态方法和变量。 More specifically, I'd like to gain access to all of the functions in Math
. 更具体地说,我想访问Math
所有函数。
I'm looking for functionality similar to: 我正在寻找类似于以下功能:
for x in Math
console.log (x + ": " + Math[x])
Is this possible? 这可能吗?
来自上一个stackoverflow
问题: 如何列出Math对象的所有属性?
Object.getOwnPropertyNames( Math )
Yes but what you need to do is iterate over the Object's prototype. 是的,但是您需要做的是迭代对象的原型。 In CoffeeScript it would look like this: 在CoffeeScript中,它看起来像这样:
for key, value of MyClass.prototype
console.log key, ':', value
EDIT: 编辑:
In JavaScript it would be this: 在JavaScript中,可能是这样的:
var i;
for (i in MyClass.prototype) {
// This condition makes sure you only test real members of the object.
if (Object.prototype.hasOwnProperty.call(MyClass.prototype, i)) {
console.log(i, ':', MyClass.prototype[i]);
}
}
EDIT 2: 编辑2:
One caveat: this will not work with native JavaScript constructors so Math
is a bad example. 一个警告:这不适用于本机JavaScript构造函数,因此Math
是一个不好的例子。 If you are using custom class constructors, it will work fine. 如果您使用的是自定义类构造函数,则可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.