admin 管理员组文章数量: 1086019
Using CoffeeScript, I would like to be able to iterate over the static methods and variables of a class. More specifically, I'd like to gain access to all of the functions in Math
.
I'm looking for functionality similar to:
for x in Math
console.log (x + ": " + Math[x])
Is this possible?
Using CoffeeScript, I would like to be able to iterate over the static methods and variables of a class. More specifically, I'd like to gain access to all of the functions in Math
.
I'm looking for functionality similar to:
for x in Math
console.log (x + ": " + Math[x])
Is this possible?
Share Improve this question edited Oct 3, 2013 at 17:31 JeremyFromEarth asked Oct 3, 2013 at 17:25 JeremyFromEarthJeremyFromEarth 14.4k5 gold badges36 silver badges47 bronze badges2 Answers
Reset to default 10From a previous stackoverflow
question: How can I list all the properties of Math object?
Object.getOwnPropertyNames( Math )
Yes but what you need to do is iterate over the Object's prototype. In CoffeeScript it would look like this:
for key, value of MyClass.prototype
console.log key, ':', value
EDIT:
In JavaScript it would be this:
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:
One caveat: this will not work with native JavaScript constructors so Math
is a bad example. If you are using custom class constructors, it will work fine.
本文标签:
版权声明:本文标题:javascript - Is it possible to iterate over the static variables and methods of a class with CoffeeScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1743995289a2515464.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论