[英]Why does the fat-arrow not bind to the current environment in loop comprehensions?
如果我编译此CoffeeScript:
funcs = ((=> console.log i) for i in [0..2])
funcs[0]() // Prints 3
funcs[1]() // Prints 3
funcs[2]() // Prints 3
它产生以下JavaScript:
(function() {
var funcs, i;
funcs = (function() {
var _i, _results,
_this = this;
_results = [];
for (i = _i = 0; _i <= 3; i = ++_i) {
_results.push(function() {
return console.log(i);
});
}
return _results;
}).call(this);
funcs[0]();
funcs[1]();
funcs[2]();
funcs[3]();
}).call(this);
我认为它将具有:
_results.push((function(i) {
return function() {
return console.log(i);
}})(i));
有人可以解释为什么不这样做吗?
粗箭头this
词法上绑定this
绑定,而不是每个变量都绑定。 使用do
通过IIFE捕获变量。
funcs =
for i in [0..2]
do (i) ->
-> console.log i
闭包不是这样工作的。 当您从另一个函数范围返回一个函数时,将得到一个闭包:
var closure = (function(i) {
return function() {
console.log(i);
};
})(i);
这可以通过以下丑陋的CoffeeScript来实现(这里不需要粗箭头):
funcs = ((do (j=i) -> -> console.log j) for i in [0..2])
我建议您不要将其写为一行。
好的,在查看了CoffeeScript文档之后,我相信我已经回答了我自己的问题。 =>
仅将函数绑定到this
的当前值。 我错误地认为它会将所有变量都绑定到它们的当前值。
...虽然具有这样的功能会很整洁。 也许->>
吗?
当您将咖啡转换为javascript时,会得到绑定示波器的函数。 问题是:
funcs = (function() {
var _i, _results,
_this = this;
_results = [];
for (i = _i = 0; _i <= 3; i = ++_i) {
_results.push(function() {
return console.log(i);
});
}
return _results;
}).call(this);
在其中,变量i是绑定的,但是到您调用该函数时,该值为3,并且在每次调用该函数时仍为3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.