An in depth understanding of scope and context in Javascript

  • 2020-07-21 06:45:30
  • OfStack

An overview of the

The implementation of scope and context in Javascript is unique to the Javascript language, which to some extent is 10 points flexible. Functions in Javascript can take on a variety of contexts, and scopes can be encapsulated and saved. Because of these features, Javascript also provides many useful design patterns. However, scope and context are also common areas of confusion for Javascript programmers in development.
The following will introduce you to the concepts of scope and context in Javascript and how they differ.

Scope VS context

The first important point to make is that scope and context are not the same thing, they don't refer to the same thing. As a front end of the dish force, often see 1 some articles to mix up these two concepts, the result of some things look more do not understand. The two concepts seem to have been confused for a long time. So, I've looked up a lot of material, and I'll explain these two concepts briefly. : stuck_out_tongue_closed_eyes:
In Javascript, when a function is called, there is a scope and context bound to the function at 1. Basically, scope is function based and context is object based. In other words, scope applies to the access to the variables in the function when the function is called. The context usually refers to the value of the "this" keyword, which is a reference to the object that owns the currently executing code.

Variable scope

Variables can be defined in local or global scope, called local variables and global variables, respectively. A global variable is a variable that is declared outside of the function and can be accessed anywhere in the program. A local variable is a variable defined in the body of a function. It can only be accessed within the body of the function or within a nested function, and cannot be accessed outside of the function.
Javascript does not currently support block-level scopes (variables defined in if, switch, for, and so on). This means that variables defined within the block are also accessible outside the block. However, in ES6, we can define block-level scope using the "let" keyword.
And for scope, you can look it up in other sources, but it's a little bit simpler.

"this" context

The context (context) usually depends on how the function is called. When a function is called as a method on an object, "this" refers to the object calling the function.


var obj={
    foo:function (){
        console.log(this === obj);
    }
};
obj.foo();   // The output true

Similarly, when we create a new object using the "new" keyword, this refers to the newly created object.

function foo(){
    console.log(this);
}
foo();         // The output window
var obj=new foo();     // The output foo {}

One thing to note is that when a function in the global scope is called, this refers to the global object, or window in the browser context. However, if you run the code in strict mode, "this" is set to "undefined"
Execution Context (Execution Context)

Javascript is a single-threaded language, which means that when Javascript runs in the browser, it can only do one thing at a time, and everything else will be in the method queue, waiting to be processed.

1. When the Javascript code file is loaded by the browser, the latest entry by default is a global execution context. When a function is called in a global context, the program is left inside the called function, and the Javascript engine creates a new execution context for the function and pushes it to the top of the execution context stack. The browser always executes the context that is currently on the top of the stack. Once the execution is complete, the context is popped off the top of the stack and then into the context execution code below. In this way, the context in the stack is executed in sequence and the stack pops out until the global context is returned.

2.1 The execution contexts can be divided into two phases: the creation phase and the execution phase. During the creation phase, the javascript interpreter first creates a variable object (also known as an "active object", activation object). An active object consists of variables, function declarations, and parameters. At this stage, the scope chain of the function is initialized and the object referenced by this is determined. The next step is the execution phase, where the code is interpreted and executed.
In the Javascript code, you can have any number of function contexts, and we already know that when a function is called, the Javascript interpreter creates a new context and a private scope, and that any variables declared inside the function cannot be accessed directly outside the current function scope.

3. From the above explanation, we have a basic idea of the "execution context" of a function, but this is also one of the most confusing places. The "execution context" in Javascript refers primarily to the scope, rather than the "this context" in section 4 above. There are many similar confusing concepts in Javascript, but once we figure out what each concept refers to, we won't be confused any more, so hopefully you will be able to distinguish between the "execution context" and the "this context".

In a simple one-sentence summary, execution context is a scope-related concept, although it may be a little loose.

The scope chain

For each execution context, there is a scope connection bound to it at 1. The scope chain contains the execution context active objects in the execution context stack (activation object, which sounds a bit convoluted). The scope chain determines the access of variables and the resolution of identifiers.

Code examples:


function first(){
    second();
    function second(){
        third();
        function third(){
            fourth();
            function fourth(){
                // code
            }
        }
    }
}
first();

Execute the above code and the nested functions will be executed. In the case of the above code, a scope chain is also formed, in the order from top to bottom: fourth, third, second, first, global. The function fourth has access to variables in the global scope and to any variable defined in the functions third, second, first.
One thing to note is that in the body of a function, local variables take precedence over global variables with the same name. A global variable is overwritten by a local variable if the local variable declared within the function or the function argument has the same name as the global variable.
In simple terms, every time we try to access a variable, the program looks for the variable in the current function scope, if not, it follows the scope chain to the upper level of the function until it is found, and if not, it returns undefined.

conclusion

This article introduces the concepts of context and scope in javascript, and there are several more important concepts in javascript, such as closures, which I will write about later on


Related articles: