JavaScript Advanced Programming (4th Edition) Reading Sharing Note Recording
Applicable to comrades who are just getting started
execution context
The context of a variable or function determines what data they can access, and how they behave.
In browsers, the global context is what we often call
the window
object ( Chapter
12
will introduce it in detail), so all
global variables and functions defined through
var
will become properties and methods of the window object .
Example:
var color = "blue";
function changeColor() {
let anotherColor = "red";
function swapColors() {
let tempColor = anotherColor;
anotherColor = color;
color = tempColor;
// 这里可以访问 color、anotherColor 和 tempColor
}
// 这里可以访问 color 和 anotherColor,但访问不到 tempColor
swapColors();
}
// 这里只能访问 color
changeColor();
The above code involves
3
contexts:
Global context ,
local context for
changeColor()
and local context for s wapColors() .
- The inner context can access everything in the outer context through the scope chain, but the outer context cannot access anything in the inner context.
- Each context can go to the upper level context to search for variables and functions, but any context cannot go to the lower level context to search
variable declaration
Function scope declaration using var
- When declaring a variable with var , the variable is automatically added to the closest context.
- var declarations are brought to the top of the function or global scope, before all code in the scope - 'variable hoisting'
Block-scoped declarations using let
- The new let keyword in ES6 is very similar to var , but its scope is block-level , which is also a new concept in JavaScript
- Block-level scope is delimited by the nearest pair of curly braces {}
-
if blocks, while blocks, function blocks, and even individual blocks are also the scope of let declaration variables
Another difference between let and var is that it cannot be declared twice in the same scope. Duplicate var declarations are ignored, and duplicate let declarations raise a SyntaxError .