4

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?

JeremyFromEarth
  • 14,344
  • 4
  • 33
  • 47

2 Answers2

10

From a previous stackoverflow question: How can I list all the properties of Math object?

Object.getOwnPropertyNames( Math )
Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353
-1

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.

rescuecreative
  • 3,607
  • 3
  • 18
  • 28
  • You didn't check it, did you? – Artyom Neustroev Oct 03 '13 at 17:46
  • Sorry guys. You're right. It doesn't work because Math is a native constructor. This only works on custom constructors. See my edit. – rescuecreative Oct 03 '13 at 17:50
  • So, is this just not at all possible then? – JeremyFromEarth Oct 03 '13 at 20:29
  • Sorry @jeremynealbrown I don't think so. And I think the reason why is that those functions are not normal functions and wouldn't work if you tried to apply them in other contexts. For example, this line: `console.log(Array.prototype.map)` yields this result: `function map() { [native code] }`. That [native code] part means the function is not implemented in JavaScript so it's special and apparently they don't want you to be able to do other things with it. – rescuecreative Oct 03 '13 at 22:54