开发者

How to use Javascript's for (attr in this) with Coffeescript

In Javascript, the "for (attr in this)" is often dangerous to use... I agree. That's one reason I like Coffeescript. However, I'm programming in Coffeescript and have a case where I need Javascript's "for (attr in this)". Is there a good way to do this in Coffeescript?

What I am doing now is writing a bunch of logic in embedded raw Javascript, 开发者_如何学Gosuch as:

...coffeescript here...
for (attr in this) {
  if (stuff here) {
    etc
  }
}

It'd be nice to use as little Javascript as possible... any suggestions for how I can achieve this and maximize my use of Coffeescript?


Instead of for item in items which iterates through arrays, you can use for attr, value of object, which works more like for in from JS.

for own attr, value of this
  if attr == 'foo' && value == 'bar'
    console.log 'Found a foobar!'

Compiled: https://gist.github.com/62860f0c07d60320151c

It accepts both the key and the value in the loop, which is very handy. And you can insert the own keyword right after the for in order to enforce an if object.hasOwnProperty(attr) check which should filter out anything from the prototype that you don't want in there.


Squeegy's answer is correct. Let me just amend it by adding that the usual solution to JavaScript's for...in being "dangerous" (by including prototype properties) is to add a hasOwnProperty check. CoffeeScript can do this automatically using the special own keyword:

for own attr of this
  ...

is equivalent to the JavaScript

for (attr in this) {
  if (!Object.prototype.hasOwnProperty(this, attr)) continue;
  ...
}

When in doubt about whether you should use for...of or for own...of, it's generally safer to use own.


You can use for x in y or for x of y depending on how you want to interpret a list of elements. The newest version of CoffeeScript aims to solve this problem, and you can read about its new use with an issue (that has since been implemented and closed) here on GitHub

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜