全局命名空间,这在循环的CoffeeScript在此代码
问题描述:
class MyClass
myfun: (arg) ->
for x in arg
do ->
...
范围的循环之外是MyClass的,而循环内(它是一个匿名函数)的范围变为存在domWindow。
为什么会出现这种情况?我怎样才能防止它?我的主要问题是如果范围更改,我无法访问MyClass类中的其他函数。
感谢
答
使用fat arrow语法的功能绑定到当前环境:
class MyClass
myfun: (arg) ->
for x in arg
do =>
...
这是因为do
关键字只是调用没有任何背景的功能,所以它默认为window
目的。
do -> ...
是相当于
(function() {
...
}());
很好的回答。有关'this' /'@'如何在JavaScript/CoffeeScript中工作的更多信息,请参阅[JavaScript Garden](http://javascriptgarden.info/#function.this)或(plug)[我的CoffeeScript书](http: //pragprog.com/book/tbcoffee/coffeescript)。 –