[英]Why does the fat-arrow not bind to the current environment in loop comprehensions?
If I compile this CoffeeScript: 如果我编译此CoffeeScript:
funcs = ((=> console.log i) for i in [0..2])
funcs[0]() // Prints 3
funcs[1]() // Prints 3
funcs[2]() // Prints 3
it produces this JavaScript: 它产生以下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);
I would think it would instead have: 我认为它将具有:
_results.push((function(i) {
return function() {
return console.log(i);
}})(i));
Could someone explain why it's not doing that? 有人可以解释为什么不这样做吗?
Fat arrow binds this
lexically, not every variable. 粗箭头
this
词法上绑定this
绑定,而不是每个变量都绑定。 Use do
to capture variables using an IIFE. 使用
do
通过IIFE捕获变量。
funcs =
for i in [0..2]
do (i) ->
-> console.log i
This is not how closures work. 闭包不是这样工作的。 You get a closure when you return a function from another function scope:
当您从另一个函数范围返回一个函数时,将得到一个闭包:
var closure = (function(i) {
return function() {
console.log(i);
};
})(i);
This can be achieved via this ugly CoffeeScript (no need for a fat arrow here): 这可以通过以下丑陋的CoffeeScript来实现(这里不需要粗箭头):
funcs = ((do (j=i) -> -> console.log j) for i in [0..2])
I'd recommend to not write this as a single line though. 我建议您不要将其写为一行。
Okay, so after looking at the CoffeeScript documentation, I believe I've answered my own question. 好的,在查看了CoffeeScript文档之后,我相信我已经回答了我自己的问题。
=>
only binds the function to the current value of this
. =>
仅将函数绑定到this
的当前值。 I had mistakenly assumed it bound all variables to their current value. 我错误地认为它会将所有变量都绑定到它们的当前值。
...although it would be neat if it had a feature like that. ...虽然具有这样的功能会很整洁。 Maybe
->>
? 也许
->>
吗?
When you convert that coffee to javascript, you're getting a function that IS binding the scope. 当您将咖啡转换为javascript时,会得到绑定示波器的函数。 The problem is that:
问题是:
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);
in there, the variable i is bound, but by the time you call the function the value is 3, and remains in 3 every time you call the function. 在其中,变量i是绑定的,但是到您调用该函数时,该值为3,并且在每次调用该函数时仍为3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.