Evan Martin (evan) wrote in evan_tech,
Evan Martin
evan
evan_tech

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).
Tags: programming languages
Subscribe
  • Post a new comment

    Error

    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 17 comments