最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to iterate over the static variables and methods of a class with CoffeeScript? - Stack Overflow

programmeradmin7浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论