JavaScript series ---- scope chain and Closure

Source: Internet
Author: User

JavaScript series ---- scope chain and Closure
1. Scope chain 1. 1. Starting with scope, we have to start with scope. Because the so-called scope chain is composed of Multiple scopes. So what is scope? 1.1.1 scope is the execution environment of a function during execution. Each function has its own execution environment during execution. The ECMAScript Standard specifies that only functions have a scope in javascript. In other words, JS does not have block-level scope. For example, copy the code function getA () {if (false) {var a = 1;} console. log (a); // undefined} getA (); function getB () {console. log (B) ;}getb (); // ReferenceError: B is not defined copy the two pieces of code above. The difference is: In the getA () function, there is a declaration of variable a, while the getB () function does not have a declaration of variable B. Another point is that the declaration in the scope is in advance. 1.1.2. in the preceding getA () function, you may still be wondering why a = "undefined" is declared in the scope. The specific reason is that the declaration in the scope is earlier: So getA () the function is equivalent to the following syntax: function getA () {var a; if (false) {a = 1}; console. log (a); since the variable declaration is mentioned in advance, you only need to clarify three problems: 1. what is variable 2. what is variable Declaration 3. when is the statement in advance. What is a variable? There are two types of variables: Common variables and function variables. Common variables: all variables identified by var are common variables. For example, var x = 1; var object = {}; var getA = function () {}; // the above three variables are common variables, however, all three equations have value assignment operations. Therefore, we need to clarify the description and value assignment. Declaration refers to var x; Value assignment refers to x = 1; function variable: function variable refers to the following, and fun is a function variable. Function fun () {}; // This refers to the function variable. function variables are also called function declaration. Like the following, it is not a function declaration, but a function expression var getA = function () {}// This is a function expression var getA = function fun (){}; // This is also a function expression, and there is no function declaration. For more information about the differences between function declarations and function expressions, see the javascript series-function Chapter 2. What is variable declaration? Variables include common variables and function variables. Therefore, the declaration of variables includes the declaration of common variables and function variables. Normal variable declaration var x = 1; // Declaration + assignment var object ={}; // Declaration + assignment the preceding two variables always perform such var x = undefined; // declare var object = undefined; // declare x = 1; // assign an object ={}; // assign a value to the declaration and assign a value. Note that, the Declaration is completed before the code of the first line of the function is executed, and the value assignment starts during the function execution period. Therefore, the Declaration always exists before the value assignment. Moreover, the declaration period of common variables is always equal to undefined. function variable declaration refers to the following: function getA () {}; // when is the function declaration advance? The declaration of all variables is completed when the first line of code inside the function is executed. ----- For the Declaration Order, see the composition of the 1.2 Scope 1. 2. the scope of the function, that is, the execution environment of the function. Therefore, all variables declared in the function must be saved in the function scope. The variables used by a function during execution come from the following three types: 1. function parameter ---- comes from the function's internal scope 2. variables declared inside the function (common variables and function variables) ---- also comes from the internal scope of the function 3. variables from the external scope of the function are described in section 1.3. For example, var x = 1; function add (num) () {var y = 1; return x + num + y; // x comes from the external scope, num comes from the parameter (the parameter also belongs to the internal scope), and y comes from the internal scope .} So what is the scope of a function? When a function is called, the function scope exists. At this point, when the function has not started execution, start to create the function scope: function scope creation step: 1. function parameter declaration. 2. Declaration of function variables 3. Declaration of common variables. 4. The value of this pointer inside the function ...... the code inside the function starts to be executed! Therefore, here we also explain why various variables are declared before the function scope is created when the function is called. For the declaration of variables, we need to emphasize the following points: 1. When declaring a function parameter, the value of its parameter has been specified. Function add (num) {var num; console. log (num); // 1} add (1); 2. in step 2, the function variable will overwrite the previously declared Declaration of the same name. Function add (num1, fun2) {function fun2 () {var x = 2;} console. log (typeof num1); // function console. log (fun2.toString () // functon fun2 () {var x = 2 ;}} add (function () {}, function () {var x = 1 }); 3. in step 3, the declaration of common variables does not overwrite the previous function add (fun, num) {var fun, num; console. log (typeof fun) // function console. log (num); // 1} add (function () {}, 1); after all declarations are completed, the function starts to execute code !!!. The composition of the scope chain is in JS, and functions can be nested. That is to say, declaring another function inside A function is similar to this: function a () {var A = 1; function B () {// inside function A, function B is declared, this is the so-called function nesting. Var B = 2 ;}} for A, function A creates the scope of function A during execution, so function B references the scope of function A during creation, the scope of function B is similar to the following when it is executed: As shown in the preceding two figures, function B references the scope of function A during execution. Therefore, nesting such function scopes forms the so-called function scope chain. When the variable cannot be found within its own scope, it will be searched up along the scope chain step by step. If the variable still cannot be found within the global scope, an exception will be thrown. 2. The closure should first be aware that the closure is to solve a problem. So What problems does it solve? Take the following example: var funB, funC; (function () {var a = 1; funB = function () {a = a + 1; console. log (a);} funC = function () {a = a + 1; console. log (a) ;}} (); funB (); // 2 funC (); // 3. for the funB and funC functions, the value of variable A in function a is changed during running. In this case, variable a is contaminated. In this figure, variable a can be changed by the functions funB and funC, which means that the variables on the external scope chain are static variables for the internal scope, it can easily cause variable pollution. Another typical example of closure is var array = []; for (var I = 0; I <10; I ++) {var fun = function () {console. log (I);} array. push (fun);} var index = array. length; while (index> 0) {array [-- index] () ;}// the output result is all 10. The root cause of this similar problem is, I did not notice that all variables in the external scope chain are static. Therefore, in order to solve the pollution problem of such variables, a closure is introduced! How can this problem be solved? The idea is: Since the variables on the external scope chain are static, it is okay to copy the variables on the external scope chain to the internal scope !! How to copy the data? Of course, it is in the form of passing parameters through the function. Take the first example as an example: var funB, funC; (function () {var a = 1; (function () {funB = function () {a = a + 1; console. log (a) ;}} (a); (function (a) {funC = function () {a = a + 1; console. log (a) ;}} (a) ;}(); funB () | funC (); // The output result is both 2 and the value of a on the scope chain is not changed.

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.