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.