4 ms·
"A new $scope object from a parent $scope can be treated the same as the new scope inside of a function block because it's how prototypical inheritance works."
by rictic 12y ago
"A new $scope object from a parent $scope can be treated the same as the new scope inside of a function block because it's how prototypical inheritance works."
This seems rather confused. There's lexical scoping with function blocks, and there's prototypical inheritance on objects, and yes in the abstract both are used for dereferencing identifiers. The parent post's point is that Angular's $scope rules are as though every function's scope behaves like prototypical inheritance on the call site rather than lexical name resolution. This is analogous to every function call being wrapped in a 'with' statement.
- andrewstuart2 12y agoMy 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