4 ms·
My favorite language is JavaScript too, and the most annoying wart for me is function scope instead of lexical scope. For example, var closures = []; f
by cousin_it 18y ago
My favorite language is JavaScript too, and the most annoying wart for me is function scope instead of lexical scope. For example,
var closures = [];
for (var i = 0; i < 10; i++)
{
var j = i;
closures[i] = function() { alert(j); }
}
closures[0](); // outputs 9, WTF?
How to fix it:
var closures = [];
for (var i = 0; i < 10; i++) (function()
{
var j = i*i;
closures[i] = function() { alert(j); }
})(i)
closures[0](); // outputs 0 as it should
- ars 18y agoFunction scope is the entire point of closures. If it was lexical scope it would not be a closure, it would just be a regular function. Just pass in j when you call it and you can have lexical scope easily. But if you changed that, a TON of code would be impossible, so I'm very happy with it working that way.
- cousin_it 18y agoNo. Function scope is the entire point of closures. If it was lexical scope it would not be a closure, it would just be a regular function. Many more languages with closures have lexical scope than function scope. Lexical scope is the entire point of closures in those languages, indeed everywhere except JavaScript. Just pass in j when you call it and you can have lexical scope easily. I don't know j when I call the closure. Give a code example. But if you changed that, a TON of code would be impossible, so I'm very happy with it working that way. I can't imagine any code that would become impossible, or even the slightest bit more difficult, if function scope were replaced with lexical. Indeed all code using function scope could be mechanically translated into a (hypothetical) lexically-scoped-JavaScript by moving every var declaration in every if/for/while/etc block up to the toplevel of the containing function. If you disagree, give a code example.
- IsaacSchlueter 18y agoYou could also do it like this: var closures = []; for (var i = 0; i < 10; i++) { var j = i; closures[i] = (function (k) { return function() { alert(k); })(j); } closures[0](); // outputs 0 The issue is that the var here is passed by reference. Ie, all 10 closures refer to the SAME "i" variable. So, when i is incremented, they see that it's been incremented. Outputing 9 is actually correct in the first case. If you want to trap the current value, you need to copy the value to a new reference, ie, by making it the argument of a function with a new scope.
- cousin_it 18y agoYeah I know how this stuff works per spec. The issue is that the var here is passed by reference. Ie, all 10 closures refer to the SAME "i" variable. So, when i is incremented, they see that it's been incremented. No, closures refer to the j variable that doesn't get incremented, only assigned to. The assignment is by value - no vars get "passed by reference", whatever this means. The actual issue is that all invocations of the loop body alias the same var j, even though it's declared inside the block. I usually wrap the whole loop body if it contains multiple variables and multiple closures closing over them - it's easier on the brain than fixing every closure creation spot. Kinda sad because JavaScript is almost the perfect language for my mind.
- IsaacSchlueter 18y agoYeah I know how this stuff works per spec. You say that, and yet, you seem not to understand it. Perhaps you know how it works, but have not thought through the implications of it working any differently? No, closures refer to the j variable that doesn't get incremented, only assigned to. ... The actual issue is that all invocations of the loop body alias the same var j, even though it's declared inside the block. You're doing it wrong. Javascript doesn't have block-level scope. It only has functional scope. In the process of parsing an execution context, all "var" statements (and named function declaration statements, which are a special sort of "var") are handled first, and only once. A var inside a loop still only creates the variable once, scoped to the function. So, your code sample is actually equivalent to: var closures = [], j = undefined; for (var i = 0; i < 10; i++) { j = i; closures[i] = function() { alert(j); } } closures[0](); // outputs 9, duh ;) You have one "j" variable that is shared by all 10 closures. When you set "j" in loop iteration 9, the closure created in iteration 0 faithfully sees that change. Closures tracking changes to variables in the parent function is not a wart. Consider this code: var thing = (function () { var privateData = "foo"; return { set : function (x) { privateData = x; }, get : function () { return privateData; } }; })(); If closures "trapped" outer values at their current state, then no matter how you called thing.set(), it would always return "foo" from thing.get(). Also, it would be much more expensive to keep track of completely independent contexts. (You could argue that these side effects make js a less pure functional language, and you'd be correct; another, less clear, argument could be made that this makes javascript less good, and I'd disagree.) However, your complaint seems not to be about closures or shared activation objects per se, but rather about the lack of block-level scope. Since "j" is created inside a set of braces, you seem to suggest that there ought to be multiple "j" variables created, which are each forgotten at the end of the loop. That's how C++ does it. But javascript is not C++. Javascript is javascript. And only functions create scope in javascript. IMO, this is not a wart. Doing otherwise would mean that every "while", "for", "switch", "if", and "else" would have to create an activation object, which would get quite expensive and complicated. If you find it confusing that a var inside a loop is only created once, then take Crockford's advice, and always put all "var" statements at the start of a function. Personally, I disagree with him on this point, because I find it more useful to "var" variables near their use so that moving code around doesn't accidentally result in leakage to the global scope.