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 badges
Add a ment  | 

2 Answers 2

Reset to default 10

From 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.

本文标签:

Error[2]: Invalid argument supplied for foreach(), File: /www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm, Line: 58
File: /www/wwwroot/roclinux.cn/tmp/route_read.php, Line: 205, include(/www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm)
File: /www/wwwroot/roclinux.cn/tmp/index.inc.php, Line: 129, include(/www/wwwroot/roclinux.cn/tmp/route_read.php)
File: /www/wwwroot/roclinux.cn/index.php, Line: 29, include(/www/wwwroot/roclinux.cn/tmp/index.inc.php)