Combining code and text to explain the scope and scope chain _ basics in JavaScript

Source: Internet
Author: User
Tags documentation variable scope

The first three paragraphs describe the scope of the code

========== example 1==========
 
var scope= ' global ';
function fn () {
  alert (scope);
  var scope= ' local ';
  alert (scope);
}
fn ();    Output results?
alert (scope);//output result?
 
//=========== Example 2==========
 
var scope= ' global ';
function fn () {
  alert (scope);
  Scope= ' local ';
  alert (scope);
}
fn ();    Output results?
alert (scope);//output result?
 
//=========== Example 3=========
 
var scope= ' global ';
function fn (scope) {
  alert (scope);
  Scope= ' local ';
  alert (scope);
}
fn ();    Output results?
alert (scope);//output result?

These three pieces of code only minor differences, but the results are very different, example 1 output [Undefined, local, global], example 2 respectively output [Global, local, local], example 3 results output [undefined, local, global], If you can't answer correctly, you don't understand the scope characteristics of JavaScript.

What is a scope?

One might ask: what is the scope of variable a? Then again: What is the scope of function a? What are the scopes of variables and functions, respectively?

Let's take a look at what "scope" means, "scope" is "action" and "field".

    • Function: Access, operation, call ...
    • Domain: area, range, space ...

Scopes are the accessible range of variables and functions, or areas where a variable or function works.

Scope of the 1.javascript function:

The area within the function is the scope of the function, and the variables and functions can access the operation in this area. The area outside the outermost function is called the global scope, and the area within the function is called the local scope.

Scope of 2.javascript variables:

In the source code, the variable is in the area where the variable is scoped and the variable can be accessed within the region. A variable defined on a global scope is called a global variable, and a variable defined within a function is called a local variable.

Simple to understand, JS source code by the function {} divided into a piece of the area, these areas change identity is a function or a variable scope, the scope of variables and functions in the source code may refer to the same area.

Scope chain
Scope Chain is a variable and function lookup mechanism within JavaScript that determines the scope of variables and functions, that is, the scope, the role of the scope chain, and the three examples of the previous article are understandable, So that we know the reason why.

The scope chain is the concept in the ECMAScript-262 documentation, the JavaScript engine is implemented by the ECMAScript-262 documentation, and understanding how the JavaScript engine works helps us understand the characteristics of JavaScript, But the vast majority of JS programmers do not understand very low-level technology, so read the ECMAScript-262 documentation, we can have an intuitive way to simulate how the JavaScript engine works.

This article will be through the 1999 years of ecmascript-262-3th Third edition to explain the formation principle of the scope chain, will introduce the implementation environment, variable objects and active objects, arguments objects, scope chain and other concepts. The fifth edition of ecmascript-262-5th was released in 2009, with the different concepts of variable objects and active objects being eliminated, and the introduction of new concepts such as lexical environment (lexical environments), environmental Records (Enviromentrecord), So the concept of two versions should not be confused.

1. Implementation environment (Execution contexts)

The execution Environment (Execution contexts) is also translated into the execution context, and when the parser enters the executable code of the ECMAScript, the parser enters an execution environment, where the execution environment of the activity consists of a logical stack, and the execution environment at the top of the logical stack is the currently running execution environment.

Note: There are three kinds of executable code, Global, function, and eval in the ECMAScript, which is the world executable code and functions as function executable code. Logic stack is a special data storage format, characterized by ' advanced, first out ', adding data will first be pressed into the top of the logical stack, delete data must first be deleted from the top.

Variable objects (Variable object), active objects (activation object), and Arguments objects (Arguments object)

Each execution environment has a variable object associated with it, and when the parser enters the execution environment, a variable object is created, and the variable object holds the reference to the variables and functions declared in the current execution environment.

A variable object is an abstract concept, in different execution environments, variable objects have different identities, and before the parser enters any execution environment, a global object is created, and when the parser enters the global execution environment, the global object acts as a variable object, and when the parser enters a function, An active object is created to act as a variable object.

2. Two stages when the parser processes the code

We all know that JavaScript parser is a section of parsing code, for the hair? This involves two stages in which the parser processes the code, parsing the code and executing the code.

When the parser enters the execution environment, the variable object adds the variables and functions declared in the execution environment as its properties, which means that the variables and functions are available before the declaration, and the variable value is undefined, which is why the variable and function declaration elevation (hoisting) At the same time the scope chain and this determines that this process is the parsing phase, commonly known as pre-resolution. The parser then starts executing the code, adds a reference to the variable, and gets the execution result, which is the execution phase.

Two delicious chestnuts:

var a=123;
var b= "abc";
Function C () {
  alert (' one ');
}

After code resolution in the above global environment executes, the global object is held as a variable object and the following data is saved.

function Testfn (a) {
  var b= "123";
  Function C () {
    alert ("abc");
  }
 
TESTFN (10);

When the parser enters the function execution environment, an active object is created as the variable object, and the active object creates a arguments object, and the arguments object is a collection of parameters that is used to save the arguments, which is what we can use when we write the function arguments[0] And so on to use the parameters of the reason.

3. Scope chain (Scope Chain)

Each execution environment has an associated scope chain, which is defined when the parser enters the execution environment, and the scope chain is a list of objects that retrieve variables and functions in each variable object, which guarantees that the execution environment has access to which variables and functions, for example, a chestnut.

var a= ' 123 ';
function Testfn (b) {
  var c= ' abc ';
 
  function testFn2 () {
    var d= ' EFG ';
    alert (a);
  }
 
  TestFn2 ();
}
 
TESTFN (10);

Variable A is not declared within the TESTFN2, why TESTFN2 can call global variable a? How did the whole process come about? Take a look at the picture below.

When the parser enters the global execution environment, it is only found in the global object when the variables and functions are invoked.

When the parser enters the TESTFN function execution Environment, the function internal property [[scope]] First fills in the global object, and then the Testfn active object is added to the global object before it forms a scope chain.

When the parser enters the TESTFN2 function execution Environment, the function internal property [[scope]] first fills in the parent's scope chain, and then adds the current TestFn2 active object to the front of the scope chain to form a new scope chain.

When TESTFN2 calls variable A, it first looks in the current TestFn2 active object and, if not found, goes up the scope chain, looks up the variable A in the Testfn active object, and then looks up the scope chain if it is not found until it is found in the last global object, otherwise the error occurs. Therefore, the function can call the external environment variables, the external environment cannot call variables inside the function, which is the principle of scope characteristics.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.