- Lexical stage
- Of lexical
- Source code check characters
- Lexical scoping
- When writing code that will block scope variables and decide where to write
- Scope search stops at the first match of the identifier
- So, there will be overriding the same name identifier
- Scope always starts from the most inner scope in which the runtime
- Progressively outwardly along scope chain
- To sum up, running, begin at the innermost scope for variables, can not find the scope chain along to find out, first find a matching identifier, OK
- Of lexical
- Lexical scope change
- eval
function foo(str, a) { eval(str); console.log(a, b); } var b = 2; foo("var b = 3;", 1); // 1, 3
- eval in strict mode to no avail
function foo(str) { "use strict"; eval( str ); console.log( a ); // ReferenceError: a is not defined } foo( "var a = 2" );
- In strict mode, eval has its own lexical scope at runtime
- Tag String the eval (..) containing the declaration statement may insert, modify lexical scoping runtime
- with
var obj = { a: 2, b: 3 }; function fo(obj) { with (obj) { b = 5; } } var o = { b: 33 }; var p = { a: 23 }; fo(o); console.log(o.b); // 33 fo(p); console.log(p.b); // undefined
- O the object has attributes; object without attribute B p, does not create the property
- statement with a reference to the object as the scope to deal with, as the attributes of the object identifier scopes, create a new runtime lexical scope .
- eval and with the optimization of the engine scope effect at compile time, it will start to slow down.
- eval
- Scope and function block scope
Internal hide implementation
The minimum authorization principle (the principle of minimal exposure)
- Minimal exposure necessary contents.
So not all variables and functions declared in the global scope
function doSomething(a) { b = a + doSomethingElse(a * 2); console.log(b * 3); } function doSomethingElse(a) { return a - 1; } var b; doSomething(2); // 15
B variables and functions doSomethingElse () is a function doSomething () private content, access to external scope can be dangerous, will be private content hidden within the function.
function doSomething(a) { var b; function doSomethingElse(a) { return a - 1; } b = a + doSomethingElse(a * 2); console.log(b * 3); }
Hidden Benefits
Lexical scoping
Guess you like
Origin www.cnblogs.com/wydumn/p/11575435.html
Recommended
Ranking