Created
April 14, 2012 03:22
-
-
Save crystalneth/2381837 to your computer and use it in GitHub Desktop.
Coffeescript closure fail?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
series = [1,2,3] | |
fs = [] | |
for i in series | |
console.log "Pushing #{i}" | |
fs.push (-> i) | |
for f in fs | |
console.log f() | |
coffee test.coffee | |
Pushing 1 | |
Pushing 2 | |
Pushing 3 | |
3 | |
3 | |
3 | |
# Why does this closure not work as expected? How can I get it to work? |
The do keyword is what I ended up with:
series = [1,2,3]
fs = []
for i in series
do (i) ->
console.log "Pushing #{i}"
fs.push (-> i)
for f in fs
console.log f()
Generated js:
(function() {
var f, fs, i, series, _fn, _i, _j, _len, _len2;
series = [1, 2, 3];
fs = [];
_fn = function(i) {
console.log("Pushing " + i);
return fs.push((function() {
return i;
}));
};
for (_i = 0, _len = series.length; _i < _len; _i++) {
i = series[_i];
_fn(i);
}
for (_j = 0, _len2 = fs.length; _j < _len2; _j++) {
f = fs[_j];
console.log(f());
}
}).call(this);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think
i
is used out of the higher scope.But you can copy
i
into a new scope and it works ... it also is pretty ugly.