Reputation: 14344
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?
Upvotes: 4
Views: 4639
Reputation: 231385
From a previous stackoverflow
question: How can I list all the properties of Math object?
Object.getOwnPropertyNames( Math )
Upvotes: 10
Reputation: 3859
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.
Upvotes: -1