标签:
Source:https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch1.md
Common Compliation Steps
var a = 2;
. This program would likely be broken up into the following tokens: var
, a
, =
, 2
, and ;
. Whitespace may or may not be persisted as a token, depending on whether it‘s meaningful or not.a
should be considered a distinct token or just part of another token, that would be lexing.var a = 2;
might start with a top-level node called VariableDeclaration
, with a child node called Identifier
(whose value is a
), and another child called AssignmentExpression
which itself has a child called NumericLiteral
(whose value is 2
).Complier Model in JS
LHS & RHS
function foo(a) { console.log( a ); // RHS of console Object, LHS of parameter in log } foo( 2 ); // RHS of foo // inplied a = 2 // LHS of a
function foo(a) { var b = a; // LHS of b, RHS of a return a + b; // RHS of a, RHS of b } var c = foo( 2 ); // LHS of c, RHS of foo // implied a = 2 // LHS of a
Nested Scope
function foo(a) { console.log( a + b ); } var b = 2; foo( 2 ); // 4
The RHS reference for b
cannot be resolved inside the function foo
, but it can be resolved in the Scope surrounding it (in this case, the global).
Error
function foo(a) { console.log( a + b ); // RHS can not find b in the scopes, results in a ReferenceError being thrown by the Engine b = a; } foo( 2 );
If the Engine is performing an LHS look-up, and it arrives at the top floor (global Scope) without finding it, if the program is not running in "Strict Mode" [^note-strictmode], then the global Scope will create a new variable of that name in the global scope, and hand it back to Engine.
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4615517.html