A simple understanding of ES5 and ES6 scopes

      If you are still unclear about ES5 and ES6, you can read it first: Introduction and Differences between JavaScript, ES5 and ES6 - Fu Heng - Blog Park

https://www.cnblogs.com/fuheng01/articles/JS.html

ES5 scope

The only thing that can create scope in js is function

{
  let a = 1;
  var b = 2;
}
console.log(a); // a is not defined
console.log(b); // 2

As above: the scope of var is the function body where it is located; the scope of let is the code block where it is located

Use var to declare a variable in a function, that variable will be regarded as a local variable and only exist in the function. When the function call ends, its local variable will be destroyed.

When the code is written, the scope of the variable can be determined according to the structure of the code. The scope in this case is the lexical scope. js is the scope of this method, not the dynamic scope.

scope chain

A scope chain is a line of variable objects. The scope chain is formed only when the function is executed. The front end of the scope chain is always the variable object corresponding to the execution environment in which the currently executing code is located, followed by the next (external) variable object, until the variable object of the outermost execution environment. .

The analytical lookup of variables in the variable object is to look up level by level along the scope

If the variable in the execution environment is not declared with var, then when the function is executed (the role chain will only be formed at this time), the variable object will be searched along the scope level by level, and if not found, the variable object will be declared in the global variable object. variable and initialize it. E.g:

function test() {
   a = 1;
}
test();
console.log(a); // 1

ES6 scope

ES6 introduced block scope, which explicitly allows functions to be declared inside block scope. The block-level scope is contained in { } . ES6 stipulates that in the block-level scope, the behavior of the function declaration statement is similar to let , and cannot be referenced outside the block-level scope.

For details, please refer to: https://segmentfault.com/a/1190000011900527

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324595560&siteId=291194637