2 ms·
I guess it just seems much more elegant and simple to me to have only one kind of scope in the language. One is all you need. No, closures refer to the j vari
by IsaacSchlueter 18y ago
I guess it just seems much more elegant and simple to me to have only one kind of scope in the language. One is all you need.
No, closures refer to the j variable that doesn't get incremented, only assigned to.
"Doesn't get incremented, only assigned to." I don't know what that means. How is "i++;j=i;" any different, really, than "i++;j++"?
The assignment is by value - no vars get "passed by reference", whatever this means.
"Passed by reference" ==> all the closures reference the same "j" variable. The phrase "pass by reference" is, of course, a bit of a mixed metaphor, since it's not really "passed" as an argument to a function, but rather trapped by a closure. Same difference.
The actual issue is that all invocations of the loop body alias the same var j, even though it's declared inside the block.
"Even though"? There are no blocks in javascript; only functions create scope. That's what's so awesomely simple about this language. Eh, to each his own, I guess.
Lexical scope could be introduced in the new additions to ES3.1, but I'm pretty sure it won't be. A javascript engine would be crazy to try to shoehorn it into the language now, since it would, in fact, break a lot of code in the wild.
Time to man up. :)
Modern Scheme compilers are quite clever at eliminating unneeded activation frames and closures, sometimes even converting closures into inline code.
Isn't that roughly what tracemonkey does?
- cousin_it 18y agoIsn't that roughly what tracemonkey does? Yes. Nice to see implementations are growing up. I guess it just seems much more elegant and simple to me to have only one kind of scope in the language... That's what's so awesomely simple about this language. Block scope can be viewed as only one kind of scope. :-) If you try to define a language formally, function scope and lexical scope will be about equivalent on the simplicity scale: scopes will just be tied to code blocks instead of functions. (The scope nesting machinery is needed for closures anyway.) Implementation simplicity is also about equivalent: yes, blocks have to allocate activation frames only if they're needed, but same applies to functions once you get serious about speed. The preference depends on your coding style. I find it intuitive to declare each variable in the outermost {} block that uses it, and not higher up; this intuition exactly corresponds to the formal concept of block scope. Many people naturally think like me, hence the huge number of Web articles complaining about the JS loop scope gotcha, calling it "weird", "unintuitive" and all manner of names. But as you say, to each his own. A javascript engine would be crazy to try to shoehorn it into the language now, since it would, in fact, break a lot of code in the wild. Yes. :-(