Talk about some difficult problems in JavaScript grammar (II.)

Source: Internet
Author: User
Tags define object definition execution functions variables variable access

3 problems related to the scope chain

The scope chain is a very red concept in the JavaScript language, and many programmers who learn and use the JavaScript language know that the scope chain is key to understanding some of the most important concepts in JavaScript, including this pointer, closures, and so on, Another important reason for its very red is that the scope chain is too difficult to understand, even if someone really understands it, but encounters a lot of practical problems, it will be the two monks can not touch the mind, such as the introduction of the example mentioned in the introduction, this topic is the scope of the chain, and no other content, Hope that the friends who read this article can gain.

Speaking scope chain first from the scope, the following is the definition of scope in Baidu Encyclopedia:

Scopes are important in many programming languages.

Generally speaking, the name used in a piece of program code is not always valid/usable, and the scope of the code that qualifies the name is that of the name.

The use of scope enhances the locality of program logic, enhances the reliability of the program, and reduces the name conflict.

In my best service-side language Java also has the concept of scope, Java scope is to {} as the boundary, but in the pure object-oriented language we do not need to study the scope of the depth, and do not need to think about the complex scope nesting problem, Because the depth of the scope of these languages is not going to do much good to the code we write. But it's quite different in JavaScript, and if we don't understand JavaScript's scope well we can't use JavaScript to write complex or large-scale programs.

By the definition of Baidu Encyclopedia, we know that the role of the scope is to ensure that the name of the variable does not conflict, the reality of the scene to understand that there is a person called John, John although only a name, but people who know John according to the name can only confirm who this person, but the world is called John more than one, Especially when two people named John have a intersection, we have to have a way to specify that this is not another John, then we may be based on the difference between the two major John Age: for example, a John called Da Zhangsan, the relative of another Zhang three called small Zhang three. The scope of the programming language is actually to do a similar tag, the scope will set a range, in which we are not mistaken for the true meaning of variables.

I said in Java to set the scope through {}, the variables in {} will be protected, this protection is not let {} variables are confused and contaminated by external variables. So is the way of {} Suitable for JavaScript? Let's take a look at the following example:

var S1 = "Sharpxiajun";
function ftn () {
var s2 = "XTQ";
Console.log (this);/Run Result: Window
console.log ("S1: + this.s1 +"; S2: "+ this.s2);/Run Result: s1:sharpxiajun;s2:und efined
Console.log ("S1:" + this.s1 + "; S2:" + s2);/Run Result: S1:sharpxiajun;s2:xtq
ftn ();

In the JavaScript world there is a large scope environment, which is the Window,window environment does not need to use our own way to build, page loading time page will be automatically constructed, the above code has a curly brace, this brace is the definition of the function, running, We find that the S2 variable defined within the function scope is not accessible by the Window object, so the S2 variable is protected by {}, and its lifecycle is related to the lifecycle of the function.

This example is not illustrated in JavaScript, the variable is also protected by {}, in the JavaScript language there is not a function of {}, we look at the following example:

if (true) {
var a = "AAAA";
Console.log (a);/Run Result: AAAA

We found that JavaScript {} sometimes does not have the ability to define a scope. This also shows that the scope definition in JavaScript is different from other languages such as Java.

In JavaScript the scope has a specialized definition execution context, in some books to translate this name into the execution contexts, some books translate it into the execution environment, I prefer the latter execution environment, I mentioned below the execution environment is execution Context The name is very image, this image is embodied in the word execution, execution meaning is implementation, we think of JavaScript in those situations are executed:

situation One: When the page loads in the script JavaScript under the label The code executes sequentially, and the code that can be executed belongs to the window a variable or function;

case Two: When the name of the function is followed by parentheses () , such as FTN () , which is also executing, but it performs a function.

In this way, there are two types of execution environment in javascript: the Global Execution Environment , the global environment represented by Windows , and the function execution environment represented by functions, which is what we often call local scopes .

Execution environment in JavaScript language is not an abstract concept, but there is a specific implementation, the implementation is actually an object, the object also has a name called variable object, this variable some books translated into variable objects, this is literal translation, some books called it context variables, Here I prefer the latter context variable, and the context variable mentioned below refers to the variable object. A context variable stores all the variables and functions defined in the execution environment where the context variable is stored.

The context variable for the global execution environment is accessible and is the window object, so it makes sense to say that window can represent the global scope, but the local scope is the context variable in the execution environment of the function that the code cannot access. But the JavaScript engine uses it when it processes data.

There is also a concept in the JavaScript language, its name is called execution context stack, translated into Chinese is the implementation of the environment stack, each function to be executed will first put the execution environment of the function into the execution environment stack, after the function is executed, The execution environment of this function will be ejected by the execution environment stack, for example, the above example: function execution when the execution of the function of the environment will be pushed into the execution environment stack, the function is completed, the implementation of the environment stack will be the environment pop-up, the implementation of the environment stack control will be placed in the global environment, if the function behind there are code, Then the code is then executed. If a function is nested within a function, then the execution of the nesting function is done, and the control of the executing environment stack is left to the external function, and then the other is the global execution environment.

Here's our famous scope chain coming up, when the execution environment of the function is pressed into the execution environment stack, the function is executed, and the first step of function execution is not the first line of code in the function, but rather the construction of a scope chain in the context variable, the English name of the scope chain is called scope chain , the role of the scope chain is to ensure that the execution environment has access to the variables and functions are ordered, the concept of two key meaning: access and order, we look at the following code:

var B1 = "B1";
function Ftn1 () {
var b2 = "B2";
var B1 = "BBB";
function ftn2 () {
var B3 = "B3";
B2 = B1;
B1 = B3;
Console.log ("B1:" + B1 + "; B2:" + b2 + "; B3:" + B3);/Run Result: b1:b3;b2:bbb;b3:b3
FTN2 ();
FTN1 ();
Console.log (B1);/Run Result: B1

With this example we found that the FTN2 function can access the variable b1,b2, which embodies the concept of access, and when the B1 value is changed in the FTN1 scope and the B1 variable is redefined as a FTN1 local variable, then FTN2 is B1 to the FTN1. FTN2 access to B1 does not look for B1 in the global scope, which embodies the order.

Below I would like to summarize the knowledge described above:

The title of this article is: the relevant problem of the scope chain, the meaning of the definition of the title refers to the scope chain is well-known, but the scope chain in the understanding of the vast number of programmers actually contains the meaning has been beyond the scope of the chain in JavaScript the definition of the language itself. The vast majority of programmers understand the scope chain two pieces is a scope, and the scope in the JavaScript language refers to the execution Environment executioncontext, the execution environment in JavaScript The engine is variable object that is represented by context variables, and the JavaScript engine has a concept that executes the context stack execution When the execution environment of a function is pressed into the stack of execution environments, this time it constructs an object in the context variable, the scope chainof the scope chain, which is the second piece of knowledge that the vast majority of programmers understand, The function of the scope chain is to ensure that the variables and functions that have access in the execution environment are ordered, the variables of the scope chain can only be accessed up, the variable access to the Window object is terminated, and the scope chain is not allowed to access the variable down.

Many people often think that the scope chain is the key to understanding this pointer, and that this is not true, this pointer construction occurs at the same time as the scope chain, which means that when the variable constructs the scope chain, it also constructs a This object, which also belongs to the context variable, and the The value of this variable is a copy of the context variable outside the current execution environment , which has no scope chain variables, such as code:

var B1 = "B1";
    function ftn1 () {
        console.log (this);//Run Result: Window
        var b2 = "B2";
        var B1 = "BBB";
        function ftn2 () {
             Console.log (this);//Run Result: Window
             var b3 = "B3";
            b2 = B1;
            B1 = B3;
            Console.log ("B1:" + B1 + "; B2:" + b2 + "; B3:" + B3 )//Run Result: B1:b3;b2:bbb;b3:b3
         ftn2 ();
    ftn1 ();

We see that the this pointer in function FTN1 and ftn2 is pointing to window, why? Because in JavaScript we define functions in the form of function xxx () {}, this function is part of the Global object window regardless of the definition, so the execution context of their execution environment is pointing to window.

But we all know the real code a lot of this pointer is not pointing to window, such as the following code:
Copy Code

var obj = {
Name: "Sharpxiajun",
Ftn:function () {
Console.log (this);/Run Result: Object {name= "Sharpxiajun", Ftn=function ()}
Console.log (;/Run Result: Sharpxiajun
OBJ.FTN ();//:

Run, we find here the this pointer points to object, which is strange to me the previous text is not to say that there are only two types of scope in javascript: One is the global one is a function, why here object can also create scope, then my theory is not a problem ah? So let's look at the following code:
Copy Code

var obj1 = new Object (); = "XTQ";
obj1.ftn = function () {
Console.log (this);/Run Result: Object {name= "XTQ", Ftn=function ()}
Console.log ( Result: XTQ}

OBJ1.FTN ();

These two ways of writing are equivalent, the first object definition method is called literal definition, while the second is standard writing, object is a function of the essence, so when we call the functions of the object, the external execution environment of the function is obj1 itself, That is, the external execution context variable represents the obj1, and the this pointer also points to OBJ1.

Oh, 11 o ' clock, tomorrow to go to work, today to write here, about the scope chain and the implementation of the environment and this relationship is not finished a bit, their relationship will involve the use of new, (the following text I want to bold, because this article does not speak this and new relationship, So the conclusion of this article is not complete, so it is written in a lot of content, so it's in the third part of the series.

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.