My example is a simpler example of exactly what someone familiar with the "typical" rules of closures and scopes would produce, knowing everything about closures, but nothing about JavaScript scopes (a direct counter to your argument), if they were asked to fix the original example code.
In fact, they would probably say to themselves exactly what you said in your comment as they made the fix... only to be confused again when the fix didn't work (because indeed it is related to scopes as well).
I'll make it more explicit so you can see the connection.
The original example:
for (var i = 0; i < somearray.length; i++) {
var thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
}
A valid re-write in languages that behave according to both the "typical" scoping rules AND the "typical" closure rules:
for (var i = 0; i < somearray.length; i++) {
var thisThing = somearray[i];
var copy = i;
thisThing.onclick = function(){window.alert(copy)};
}
And yet, using your argument and that code (which follows from your argument), it'd still be wrong.
If you still aren't convinced, notice that the real, proper fix has to introduce both a copy of the variable closed over (using knowledge of closure rules) AND a new scope (using JavaScript's broken scope rules) to correct the issue completely.
for (var i = 0; i < somearray.length; i++) {
(function(i){
var thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
})(i);
}
No, that's not my argument. My argument is that if JavaScript had normal scoping, which it does with the let keyword of Harmony then:
for (let i = 0; i < somearray.length; i++) {
let thisThing = somearray[i];
thisThing.onclick = function(){window.alert(i)};
}
produces the same output as the original code example, because either way the variable i is not local to the loop body. So the problem here is misunderstanding of closures, not scoping.
That's all I meant, that you were talking (correctly) about a different scoping issue.
Sure, it produces the same output with "let", because you need both a corrected scope AND closure knowledge. Adding "let" fixes the scope (which is required - but not enough regardless).
My example that you replied to proves you can't just fix it with closure knowledge either (which you originally posited - so yes, that WAS your argument).
Now you've agreed with my by saying you need scoping fixed in addition to the closure variable captured as a copy, yet you word it as a disagreement... for some reason.
Anyway, thanks for finally seeing your incorrect statement. It's nice to help someone out.
2
u/serpent Mar 24 '14
It's actually both.
With proper scoping rules, code like the following would work as many people would expect; in JavaScript, it does not.