4 ms·
My thought pattern on lexical scopes in javascript is that they're essentially a new object off of the prototype of the parent lexical scope. At least they have
by andrewstuart2 12y ago
My thought pattern on lexical scopes in javascript is that they're essentially a new object off of the prototype of the parent lexical scope. At least they have very similar properties.
In a new lexical scope, a new variable of the same name as one accessed via closure means I lose reference enclosed variable. In the same way, a new property of the same name as a property in the prototype chain means I lose reference to that property somewhere up the chain.
I have a suspicion that it's all linked lists of hashmaps under the hood, though I haven't checked the source. At the very least, prototypical inheritance and lexical scoping can definitely both be implemented that way.
- rictic 12y agoThe advantage of lexical scope over dynamic scope is predictability. You can reliably* read a javascript program and map each variable access to the scope of that variable (so can a compiler, which accounts for no small portion of the speed of modern javascript implementations). With dynamic scoping there are no guarantees about where you'll find any nonlocal variable. In practice this caused enough difficulty that the programming language community has moved steadily away from dynamic scoping. You make an interesting parallel with prototype lookup, but it's worth noting that the prevailing pattern of prototype use mimics the traditional class and instance rubric. In that situation it is also fairly easy and deterministic to pin down where in the prototype chain every identifier is defined. * with the exception of code which uses `with` statements and certain forms of eval, which is a big part of why those constructs are strongly discouraged by the community