JavaScript scope and execution context

Time:2020-11-6

JavaScript scope and execution context

The type of scope

global scope

Function scope

Block level scope (ES6)

let const

  • Duplicate declaration is not allowed
  • There is no claim escalation
  • There is a block level scope
  • The properties of top-level objects are decoupled from global variables

Temporary dead zone (TDZ)

When the JavaScript engine scans the code and finds variable declarations, they are either promoted to the top of the scope (VaR declarations are encountered) or they are placed in TDZ (let and const declarations are encountered). Accessing variables in TDZ triggers a runtime error. Only after the variable declaration statement has been executed, the variable will be removed from TDZ and can be accessed.

Block level scope in loops

for
Each time a new variable is created and the value of the variable is modified during the iteration.

var funcs = [];
for (var i = 0; i < 3; i++) {
    funcs[i] = function () {
        console.log(i);
    };
}
funcs[0](); // 3

//Solutions
var funcs = [];
for (var i = 0; i < 3; i++) {
    funcs[i] = (function(i){
        return function() {
            console.log(i);
        }
    }(i))
}
funcs[0](); // 0

for-in
In the for in loop, each iteration does not modify the existing binding, but creates a new binding.

var funcs = [], object = {a: 1, b: 1, c: 1};
for (var key in object) {
    funcs.push(function(){
        console.log(key)
    });
}
funcs[0]() //'c'

var funcs = [], object = {a: 1, b: 1, c: 1};
for (let key in object) {
    funcs.push(function(){
        console.log(key)
    });
}
funcs[0]() //'a'

var funcs = [], object = {a: 1, b: 1, c: 1};
for (const key in object) {
    funcs.push(function(){
        console.log(key)
    });
}
funcs[0]() //'a'

Reference articles: https://segmentfault.com/a/11…

Working model of scope

  • Lexical scope (static scope)
  • dynamic scope

JavaScript uses lexical scope. The scope of function is determined when the function is defined. The scope of a function is based on where the function was created.
The dynamic scope is opposite to lexical scope. The scope of a function is determined when the function is called.

For example:

var value = 1; 
function foo() { 
    console.log(value); 
} 
function bar() { 
    var value = 2; 
    foo(); 
} 
bar();
  • Assuming that JavaScript uses static scope, let’s analyze the following execution process:

To execute the foo function, first find out whether there is a local variable value from the inside of the foo function. If not, find the code in the upper layer according to the writing position, that is, the value is equal to 1, so the result will be printed as 1.

  • Suppose JavaScript adopts dynamic scope. Let’s analyze the execution process as follows:

When the foo function is executed, the local variable value is still searched from inside the foo function. If not, look for the value variable from the scope of the calling function, that is, inside the bar function, so the result will be printed 2.

As we said earlier, JavaScript uses static scope, so the result of this example is 1.

Reference articles: https://segmentfault.com/a/11…

Execution context

For each execution context, there are three important properties:

  • Variable object (VO)
  • Scope chain
  • this

Variable object (VO)

Variable object in global context

The global object is the head of the scope chain, which also means that all variables declared in the top-level JavaScript code will become properties of the global object. In the top-level JavaScript code, the keyword this can be used to refer to global objects.

Variable object in function context

In the context of a function, we use an activation object (AO) to represent a variable object.

Execution process

  1. Enter execution context
  2. Code execution
Enter execution context

When entering the execution context, the code has not been executed, and the variable object will include:

  1. All formal parameters of the function (if it is a function context)

    • The properties of a variable object consisting of a name and corresponding values are created
    • There is no argument, the property value is set to undefined
  2. Function declaration

    • The properties of a variable object are created by the name and the corresponding value (function object)
    • If a property of the same name already exists on the variable object, the property is completely replaced
  3. Variable declaration

    • An attribute of a variable object is created, which consists of a name and an undefined value;
    • If the variable name is the same as a formal parameter or function that has already been declared, the variable declaration does not interfere with existing properties of this type

for instance:

function foo(a) {
  var b = 2;
  function c() {}
  var d = function() {};

  b = 3;

}

foo(1);

After entering the execution context, the Ao is:

AO = {
    arguments: {
        0: 1,
        length: 1
    },
    a: 1,
    b: undefined,
    c: reference to function c(){},
    d: undefined
}
Code execution

In the code execution phase, the code will be executed in sequence, and the value of the variable object will be modified according to the code
In the above example, when the code is executed, the Ao is:

AO = {
    arguments: {
        0: 1,
        length: 1
    },
    a: 1,
    b: 3,
    c: reference to function c(){},
    d: reference to FunctionExpression "d"
}

Summary:

  1. Global context variable object initialization is a global object
  2. Variable object initialization for function context includes only arguments object
  3. When entering the execution context, initial attribute values such as formal parameter, function declaration and variable declaration will be added to the variable object
  4. During code execution, the property values of the variable object are modified again

Reference articles: https://segmentfault.com/a/11…

Scope chain

When searching for variables, the variable objects in the current context will be searched first. If they are not found, they will be searched from the variable objects of the execution context of the parent (the parent on the lexical level) to find the variable objects in the global context, that is, the global objects. In this way, the linked list composed of variable objects of multiple execution contexts is called scope chain.

Reference articles: https://segmentfault.com/a/11…

this

Reference articles: https://segmentfault.com/a/11…

Recommended Today

Think about open source project promoting rust search extension: quickly search rust documents in the browser address bar

Open source project name:Rust Search Extension Introduction to open source projects:Quick search for rust documents in the browser address barOpen source project type:teamProject creation time:2020 GitHub data:375 Star,18 ForkGitHub address:https://github.com/huhu/rust-search-extension Rust search extension is a plug-in that can quickly search rust documents, Crites, built-in properties and error codes in the browser address bar. It supports […]