Previous Entry Share Next Entry
03:11 pm, 17 Jan 07

js closures revisited

Today I realized I had completely misunderstood JavaScript closures, and I retract previously-nasty comments I had made about them. I think I had been confused before because I had mostly used closures in functional languages, where it's uncommon (or outlawed) to reassign variables.

For future reference: the only JS-specific language gotcha you really need to be aware of is that the only way to create a new binding (scope) is with a function, not by (as in syntactically-similar languages) with an extra curly brace.

To succinctly summarize the gotcha:
for (i = 0; i < I; ++i) {
  var j = i; // XXX we're not in a new scope
  objects[i].whatever = function() { ... };
In code like this, if the ... refers to i or j, then all of the functions refer to the same i and j and so will reference the same value at the end of the for loop (i = I, j = I-1).