First, the following are three codes that explain the scope
//=========== Example 1============== var scope='global';function fn(){ alert(scope); var scope='local'; alert(scope);}fn(); //Output result? alert(scope);//Output result? //============ Example 2============ var scope='global';function fn(){ alert(scope); scope='local'; alert(scope);}fn(); //Output result? alert(scope);//Output result? //============ Example 3=========== var scope='global';function fn(scope){ alert(scope); scope='local'; alert(scope);}fn(); //Output result? alert(scope);//Output result?These three codes have only a small difference, but the results are completely different. Example 1 outputs [undefined , local , global], Example 2 outputs [global , local , local], Example 3 outputs [undefined , local , global]. If you cannot answer correctly, it means that you have not yet understood the scope characteristics of javascript.
What is scope?
Someone may ask: What is the scope of the variable a? I asked again later: What is the scope of function a? What are the scopes of variables and functions?
Let’s first look at what “scope” means. When “scope” is broken down, it means “function” and “domain”
Scope is the accessible range of variables and functions, or the area in which variables or functions work.
1.Scope of javascript function:
The area within the function is the scope of the function, and both variables and functions can access operations in this area. The area outside the outermost function is called the global scope, and the area inside the function is called the local scope.
2. Scope of javascript variables:
In the region where the variable is located in the source code, the scope of this variable is, and the variable can be accessed and operated within this area. Variables defined in the global scope are called global variables, and variables defined in the function are called local variables.
To simply understand, JS source code is divided into areas of block by function {}. If these areas change their identity, they are the scope of a certain function or a certain variable. The scope of a variable and the scope of a function may refer to the same area in the source code.
Scope chain
Scope Chain is a variable and function search mechanism within JavaScript. It determines the scope of the variables and functions, that is, scope. Understand the principle of the scope chain, and you can understand the three examples in the previous article, so that you can know the reason and the reason.
Scope chain is a concept in the ECMAScript-262 documentation. The javascript engine is implemented according to the ECMAScript-262 documentation. Understanding the working principle of the javascript engine is conducive to our understanding of the characteristics of javascript, but most js programmers will not understand very underlying technologies. Therefore, when reading the ECMAScript-262 documentation, we can have an intuitive way to simulate the working principle of the javascript engine.
This article will explain the principle of forming scope chains through the third edition of ECMAScript-262-3th in 1999, and will introduce several concepts such as execution environment, variable objects and active objects, arguments objects, scope chains, etc. In 2009, the fifth edition of ECMAScript-262-5th was released. The difference was that the concepts such as variable objects and active objects were cancelled, and new concepts such as Lexical Environments and Environment Records were introduced, so don't confuse the concepts of the two versions.
1.Execution Contexts
Execution Contexts are also translated into execution context. When the parser enters the executable code of ECMAScript, the parser enters an execution environment. The active execution environment forms a logical stack. The execution environment at the top of this logical stack is the current running execution environment.
Note: There are three types of executable code in ECMAScript, Global, Function and Eval. The global environment is Global executable code, and functions are Function executable code. The logic stack is a special data storage format, characterized by 'first in and out, and then in and out'. Adding data will first be pushed into the top of the logic stack, and deleting data must be deleted from the top.
Variable Object, Active Object, and Arguments Object
Each execution environment has a variable object associated with it. When the parser enters the execution environment, a variable object will be created, which holds references to variables and functions declared in the current execution environment.
Variable object is an abstract concept. In different execution environments, variable objects have different identities. Before the parser enters any execution environment, a Global object is created. When the parser enters the global execution environment, the Global object acts as a variable object. When the parser enters a function, an active object will be created as a variable object.
2. Two stages when the parser processes the code
We all know that javascript parser parses the code one by one, is it a mat? This involves two stages when the parser processes the code, parsing the code and executing the code.
When the parser enters the execution environment, the variable object will add variables and functions declared in the execution environment as its properties, which means that the variables and functions are available before declaration, and the variable value is undefined. This is the reason for the promotion of variables and function declarations (hoisting). At the same time, the scope chain and this are determined. This process is the parsing stage, commonly known as pre-parsing. Then the parser starts executing the code, adds a reference to the corresponding value to the variable, and obtains the execution result. This process is the execution stage.
Let’s name two delicious chestnuts:
var a=123;var b="abc";function c(){ alert('11');}After the code parsing and executing in the above global environment, the Global object will be used as a variable object and the following data will be saved.
function testFn(a){ var b="123"; function c(){ alert("abc"); }} testFn(10);When the parser enters the function execution environment, an active object will be created as a variable object. The active object will also create an Arguments object. The arguments object is a parameter set to save parameters. This is why we can use arguments[0] and so on when writing functions.
3. Scope Chain
Each execution environment has a scope chain associated with it. It is defined when the parser enters the execution environment. The scope chain is an object list used to retrieve variables and functions in each variable object. This ensures that the execution environment has the right to access which variables and functions. For example, it is a chestnut.
var a='123';function testFn(b){ var c='abc'; function testFn2(){ var d='efg'; alert(a); } testFn2();} testFn(10);The variable a is not declared in testFn2. Why can testFn2 call the global variable a? How did the whole process happen? Please see the picture below.
When the parser enters the global execution environment, variables and functions are only found in the Global object when calling them.
When the parser enters the testFn function execution environment, the internal property of the function [[scope]] is first filled in the Global object, and then the testFn active object is added to the Global object to form a scope chain.
When the parser enters the testFn2 function execution environment, the internal property of the function [[scope]] is first filled in the parent scope chain, and then the current testFn2 active object is added to the front end of the scope chain to form a new scope chain.
When testFn2 calls variable a, first search in the current testFn2 active object. If it is not found, follow the scope chain upwards. If it is not found, look up the scope chain. If it is not found, look up the scope chain until it is found in the last Global object, otherwise an error will be reported. Therefore, variables of the external environment can be called inside the function, and variables of the external environment cannot be called inside the function. This is the principle of scope characteristics.