In-depth understanding of the scope and context in Javascript _ javascript skills

Source: Internet
Author: User
Tags variable scope
This article mainly introduces the scope and context of Javascript. this article describes the scope VS context, variable scope, "this" context, execution context (ExecutionContext), and scope chain, for more information, see Overview

The implementation of scopes and context in Javascript is unique to the Javascript language. To some extent, Javascript is very flexible. Functions in Javascript can use various contexts, and the scopes can be encapsulated and saved. Thanks to these features, Javascript also provides many useful design patterns. However, the scope and context are often confusing for Javascript programmers during development.
The following describes the concepts of scopes and contexts in Javascript and their differences.

Scope VS Context

The first important thing to note is that the scope and context are not the same concept and they refer to different things. As a front-end dish, I often see some articles mixed up these two concepts. As a result, some things become more and less understandable. These two concepts seem to have been confused for a long time. Therefore, I checked a lot of information and briefly explained these two concepts. : Stuck_out_tongue_closed_eyes:
In Javascript, when a function is called, a scope is bound to the context and function. Basically, the scope is based on functions and the context is based on objects. In other words, the scope applies to the access permissions of the variables in the function when the function is called. Context usually refers to the value of the "this" keyword. "this" is a reference to an object that owns the current code execution.

Variable Scope

Variables can be defined in local or global scopes, called Local variables and global variables respectively. A global variable is a variable declared in the external body of a function. global variables can be accessed anywhere in the program. A local variable is a variable defined in the function body. It can only be accessed in the function body or nested function, and cannot be accessed outside the function.
Currently, Javascript does not support block-level scopes (variables defined in if, switch, for, and other statements ). This means that the variables defined in the block can also be accessed outside the block. However, in ES6, we can use the "let" keyword to define the block-level scope.
For details about the scope, you can check other materials. This part is relatively simple.

"This" context

Context usually depends on the method in which the function is called. When a function is called as an object method, "this" refers to the object that calls the function.

The Code is as follows:


Var obj = {
Foo: function (){
Console. log (this = obj );
}
};
Obj. foo (); // Output true


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

The Code is as follows:


Function foo (){
Console. log (this );
}
Foo (); // Output window
Var obj = new foo (); // output foo {}


Note that when a function in the global scope is called, this references a Global Object and indicates a window in the browser environment. However, if you run the code in strict mode, "this" is set to "undefined"
Execution Context)

Javascript is a single-threaded language. That is to say, when Javascript runs in a browser, only one thing can be done at a time. Other things will be in the method queue and waiting for processing.

1. When the Javascript code file is loaded by the browser, a global execution context is entered by default. When a function is called in a global context, the program stays in the called function, and the Javascript engine creates a new execution context for the function, and press it to the top of the execution context stack. The browser always executes the current context at the top of the stack. Once the execution is complete, the context will pop up from the top of the stack and then enter the context under which the code is executed. In this way, the context in the stack is executed sequentially and the stack pops up until the global context is returned.

2. An execution context can be divided into two stages: Creation stage and execution stage. In the creation phase, the javascript interpreter first creates a variable object (also known as an "activity object", activation object ). Activity objects are composed of variables, function declarations, and parameters. At this stage, the function's scope chain is initialized, and the objects referenced by this are also determined. The next step is the execution stage. At this stage, the Code is interpreted and executed.
In Javascript code, there can be any number of function contexts. As we know, when a function is called, The Javascript interpreter creates a new context, at the same time, a private scope will be created, and no variable declared in the function can be directly accessed outside the current function scope.

3. Through the above explanation, we have a basic concept of the "execution context" of the function, but this is also the most confusing place for everyone. In Javascript, "execution context" mainly refers to the scope, rather than the "this context" in the fourth section above ". Similar obfuscation-prone concepts still exist in Javascript, but we will not be confused as long as we figure out the specific objects referred to by each concept. Therefore, we also hope that you can truly distinguish "execution context" from "this context ".

In a simple sentence, the execution context is related to the scope, although it may be less rigorous.

Scope chain

For each execution context, a scope is bound to it. The scope chain contains the execution context activity object (activation object) in the execution context stack ). The scope chain determines the access to variables and the resolution of identifiers.

Sample Code:

The Code is as follows:


Function first (){
Second ();
Function second (){
Third ();
Function third (){
Fourth ();
Function fourth (){
// Code
}
}
}
}
First ();

Execute the code above and all nested functions will be executed. As far as the code above is concerned, a scope chain will also be formed. The order of the scope chain from the top to the bottom is: fourth, third, second, first, global. The fourth function can access variables in the global scope and access any variables defined in the third, second, and first functions.
Note that in a function, local variables take precedence over global variables with the same name. If the local variables or function parameters declared in the function have the same name as the global variables, the global variables will be overwritten by the local variables.
To put it simply, every time we try to access a variable, the program will find the variable in the current function scope. If it cannot be found, it will link it to the upper layer of the function along the scope chain, until the variable is found. If the variable cannot be found, undefined is returned.

Summary

This article introduces the concepts of context and scope in javascript, and several important concepts in javascript, such as closures. These will be written into articles later ~~

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.