1. Variable scope: [P71]
This sentence is very insightful: "In ECMAScript, there are only two execution environments, the global environment and the function environment. Each function is An execution environment, including nested functions. In other words, even if variables are declared within a pair of braces, they are still accessible outside the braces." An example is given below:
for(var i=0; i<5; i ) {
var num = 20; // Variables declared in the for statement
}
alert(num); // Calling variables outside the for statement can still get num The value
also works for exception statements:
try {
var num = 20; // Variable declared in try statement
a = b; // Cause an exception
} catch(e) {
alert( num); // Calling the variable in the catch statement will get 20
} finally {
alert(num); // Calling the variable in the finally statement will get 20
}
alert( num); // Calling a variable outside the try statement will get 20
In addition to the two statements demonstrated above, a pair of curly brackets cannot form an execution environment, for example:
{ var num = 1;3 }
2. this pointer: [P83]
List here the different meanings of this in ECMAScript:
(1) Used in the global execution environment this represents the Global object, which is the window object in the browser.
(2) When this is used in a function execution environment, the situation becomes a bit complicated. If the function does not have an obvious attribute as a non-window object, but only defines the function, regardless of whether the function is defined in another function, this in this function still represents the window object. If the function is explicitly used as a property of a non-window object, then this in the function represents this object. (Of course, you can use the apply or call function to replace the default this reference, see [P88] for details)
(3) When calling a function through the new operator, the function is treated as a constructor, and this points to the constructor The object created by the function.
Reference:
"Detailed Explanation of JavaScript Basics and Case Development" Tsinghua University Press