Skip to content

Instantly share code, notes, and snippets.

@crystalneth
Created April 14, 2012 03:22
Show Gist options
  • Save crystalneth/2381837 to your computer and use it in GitHub Desktop.
Save crystalneth/2381837 to your computer and use it in GitHub Desktop.
Coffeescript closure fail?
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?
@MerlinDMC
Copy link

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.

series = [1,2,3]

fs = []
for i in series
  console.log "Pushing #{i}"
  fs.push ((i) -> (-> i))(i)

for f in fs
  console.log f()
Pushing 1
Pushing 2
Pushing 3
1
2
3

@crystalneth
Copy link
Author

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()

@crystalneth
Copy link
Author

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