Javascript understanding of the scope and the scope chain

Foreword

2771 word article, read it takes about 8 minutes.

In summary: This article explains the concept Javascript scope, scope type, scope chain such as Javascript and how to establish the scope chain and look for variables.

A flower withered, barren not the entire spring.

text

The scope and the scope chain in Javascript and many other programming languages ​​is a basic concept. Javascript but many developers do not really understand them, but Javascript is critical to grasp these concepts.

The right to understand the concept in favor of you to write better, more efficient and more concise code, so that you become a better Javascript developers.

Therefore, in this article I will explain to you what is the scope and the scope chain, as well as within the Javascript engine is operating and how they look for variables.

Without further ado, the body start :)

What is the scope

Javascript in scope talking about accessibility and visibility of variables. That is to say which parts of the entire program can access the variable, or that the variables are visible in what areas.

Why important Scope

  1. Scope The most important thing is security. Variables can only be accessed in a specific area, we can avoid an accident with the scope to make changes to a variable in the program to other locations.
  2. Scope will also reduce the pressure named. We can define the same variable name in different scopes below.

Scope of type

Javascript There are three scopes:

  1. Global scope;
  2. Function scope;
  3. Block-level scope;

1. The global scope

Any not in a function or variable declared in braces, are in global scope, variables declared at global scope can be accessed anywhere in the program. E.g:

// 全局变量
var greeting = 'Hello World!';
function greet() {
  console.log(greeting);
}
// 打印 'Hello World!'
greet();

2. Function scope

Function scope, also known as local scope, if a variable is declared inside a function it was underneath a function scope. These variables can only be accessed inside the function, not to visit outside the function. E.g:

function greet() {
  var greeting = 'Hello World!';
  console.log(greeting);
}
// 打印 'Hello World!'
greet();
// 报错: Uncaught ReferenceError: greeting is not defined
console.log(greeting);

3. The block-level scope

ES6 introduced letand constkeywords, and varkeyword is different in braces letand constvariable declarations present in the block-level scope. These variables can not be accessed outside the braces. Look at an example:

{
  // 块级作用域中的变量
  let greeting = 'Hello World!';
  var lang = 'English';
  console.log(greeting); // Prints 'Hello World!'
}
// 变量 'English'
console.log(lang);
// 报错:Uncaught ReferenceError: greeting is not defined
console.log(greeting);

As can be seen in the above code, used in braces vardeclared variable lang is accessible outside the braces. Using vara variable declared absence of block-level scope.

Nested scopes

May be a function declaration inside another function like in Javascript functions, scopes may be nested in another scope. See examples:

var name = 'Peter';
function greet() {
  var greeting = 'Hello';
  {
    let lang = 'English';
    console.log(`${lang}: ${greeting} ${name}`);
  }
}
greet();

Here we have three nested scopes, the first layer is a first block-level scope ( letdeclarations), is nested within a scope of the function ( greetfunction), the outermost layer scope is global scope.

Lexical scoping

Lexical scoping (also called static scope) the literal sense is to say in the lexical scoping stage (usually a compilation phase) to determine the implementation phase rather than determined. Look at an example:

let number = 42;
function printNumber() {
  console.log(number);
}
function log() {
  let number = 54;
  printNumber();
}
// Prints 42
log();

The above code can be seen regardless of printNumber()call where the console.log(number)prints 42. Dynamic scope different, console.log(number)this line of code printing function depends on what printNumber()and where to call.

If dynamic scope , the above console.log(number)line of code will print 54.

Use lexical scope, we can just look at the source code to determine the effect of a range of variables, but if it is before the dynamic scope, we can not determine the code execution variable range of action.

Like C, C ++, Java, Javascript, etc. Most programming languages ​​support static scope. Perl supports both dynamic scoping also supports static scope.

The scope chain

When using a variable in Javascript, the first thing to go Javascript engine will try to find the scope of the variables in the current, if not found, then its scope to find the top, and so on until you find the variable or global role has been to area.

If you still can not find the variable in the global scope, it will implicitly declare the variable (non-strict mode) or directly to an error in the global scope.

E.g:

let foo = 'foo';
function bar() {
  let baz = 'baz';
  // 打印 'baz'
  console.log(baz);
  // 打印 'foo'
  console.log(foo);
  number = 42;
  console.log(number);  // 打印 42
}
bar();

When the function bar()is called, Javascript engine first looks in the current scope variables baz, and then look for foo variable but found not found in the current scope, and then continue to look outside the scope found it (this is found in the global scope of ).

Then 42assigned to the variable number. Javascript engine will look for number variables in the current scope and outside the scope of the next step (not found).

If you are in a non-strict mode, the engine will create a numberglobal variable and to 42assign to it. But if it is in strict mode will be incorrect report.

Conclusion: When using a variable time, Javascript engine will follow up the scope chain to find the variable layer by layer, until you find the variable.

How the scope of work and the scope chain

Above we have explained the scope, type scope, now let's see Javascript engine is how to determine the scope chain variable and how to find variable.

To understand how Javascript variable is looking for, Javascript must understand the environment in the lexical concept (see: understanding the context of the implementation and execution stack Javascript in ).

What is the lexical environment

The so-called lexical environment is a kind of identifier - variable structure mapping (where the identifier refers to the names of the variables / functions, a variable is a reference to the actual object or [an array containing the object function and a type of] basic data type).

Simply put, the lexical environment is the Javascript engine used to store local variables and object references.

Note: Do not confuse the lexical environment and lexical scope, lexical scoping in the code compilation phase to determine the scope ( Translator's Note : an abstract concept), and lexical environment is the Javascript engine used to store local variables and object references ( Translator's Note : with a concept of the image).

A lexical environment like this:

lexicalEnvironment = {
  a: 25,
  obj: <ref. to the object>
}

Only when the scope of the code is executed, the engine will create a new environment for the lexical scope. Lexical Environment also records referenced by external lexical environment (ie outside the scope). example:

lexicalEnvironment = {
  a: 25,
  obj: <ref. to the object>
  outer: <outer lexical environemt>
}

How Javascript engine is variable lookups

Now that we know the concept of scope, lexical scope chain and the environment, now let's see how the Javascript engine to determine the scope and use lexical scope chain environment.

With examples do we understand these concepts above:

let greeting = 'Hello';
function greet() {
  let name = 'Peter';
  console.log(`${greeting} ${name}`); // Hello Peter
}
greet();
{
  let greeting = 'Hello World!'
  console.log(greeting); // Hello World!
}

After the above code is loaded, first we create a global lexical environment, which contains variables and functions declared in the global scope. Like this:

globalLexicalEnvironment = {
  greeting: 'Hello'
  greet: <ref. to greet function>
  outer: <null>
}

Here's outerfield (that is, outside the lexical environment) is set in order null, because the global lexical environment already is the top of the lexical environment.

We then call the greet()function, and then a new lexical environment will be created:

functionLexicalEnvironment = {
  name: 'Peter'
  outer: <globalLexicalEnvironment>
}

Here's outerfield is set to globalLexicalEnvironment, because he is outside the scope of the global scope.

Then, console.log ( `$ {greeting} $ {name}`) This line of code, Javascript engine first to find lexical environment variable in the current function of greetingand name, but only to find name, could not find greeting. Then keep looking at the top of the lexical environment greeting(this is a global environmental law lyricist). Finally found the global lexical environment greeting.

Then execute that code in braces to create a new lexical environment for the block level. as follows:

blockLexicalEnvironment = {
  greeting: 'Hello World',
  outer: <globalLexicalEnvironment>
}

Then execute console.log(greeting)this line of code, first looking at this layer lexical environment greeting, OK, find the end. At this time we will not go outside the scope (here is the global scope) to find the variables.

Note: Only letand constdeclare variables will create a new lexical environment storage, use varvariable declarations will be stored in the lexical environment of the current block (braces) are located in (or global environment lexical function lexical environment).

Conclusion: When a variable is used, Javascript Engine first lexical in the current environment to find, if you can not find find the upper lexical environment looking until I find.

in conclusion

Scope is a variable area accessible and visible, and function the same, Javascript scope can also be nested, Javascript engine will traverse the layers to find the scope of the variables used.

Javascript use lexical scoping, which means that the role of the variables will be determined at compile time.

Javascript engine uses to store the lexical environment variables and functions during program execution.

The scope and the scope chain is based on the concept Javascript in understanding the scope and the scope chain can make you become a better Javascript developers.

the above.


Limited capacity, the level of general, welcomed the errata, be grateful.

Subscribe more articles may be concerned about the public number "front-end Advanced Learning ', replies," 666 ", get a package of front-end technology books

Advanced front-end learning

Guess you like

Origin www.cnblogs.com/jztan/p/12342301.html