Understanding of the scope of JavaScript (i)

Source: Internet
Author: User

1, the first is a concept of scope: the scope is simply divided into two parts:

1) The function is the reading and writing of the program (although not complete, but for the time being understood)

2) domain is a spatial area

Then the most common two scopes in JS is <script></script> and function () {} The difference between the two can be seen as:

1) <script></script> is a global function parsed from top to bottom (when there are many <script> scopes)

2) function () {} from the Inside Out


2, the next need to have a browser to resolve the steps to understand (the scope is resolved after the execution of) browser to the JS code parsing is from the <script> tag start is divided into two steps:

1) JS pre-parsing (can be seen as a "warehouse" to parse out the things first put into this "warehouse") to resolve the things include:

①var variable JS because there is no explicit definition of variables to be specifically defined as what variables so when the browser pre-parsing to a variable, the name of the variable is placed in the "warehouse"

Regardless of what type of variable is assigned to the undefined value.

The ②function function puts the entire function block first in the "warehouse" before it is formally run

③ parameter properties and variable consistency


Then there's going to be a new problem. When pre-parsing, the most common generalization is the following two scenarios if you encounter duplicate name problems:

The ① variable leaves the function with the same name as the function (which is irrelevant to the order in which the function and the variable appear in the code) because the variable at this time is a undefined value

Function functions are also a type that is more meaningful than undefined.

② functions and functions or variables and variables are followed by overwriting the preceding function or variable (precedence principle)


2) Line-wise interpretation of code after pre-parsing begins line-by-row interpretation of the code this way the expression can modify the pre-resolved values (that is, modify the values in the "warehouse")

The specific expression can be = +-*/% + +--!  || && parameters, etc....


3. Scope Chain

If the child does not find the corresponding declaration at the time of pre-parsing, it will go to the parent until the top-level scope is found. The expression of the parent variable in the child is affected by the parent variable in detail example 4)

But in turn, the parent does not go to the child to find a variable that is not parsed when the child is pre-parsed so you want the parent to be able to get the value of the variable in the child. Specifically, you can see the following "other"

Of course, the WITH statement is often used in the scope chain to temporarily change the current scope

Specific example Analysis:

1) Renaming issues in the "warehouse"

<script>/*the analysis of the duplicate name problem the first step of pre-parsing found that there are variables and functions with the same name problem then the reserved function also has the function and function with the name of the function "after" is preserved in the last warehouse is the function block functions a () {alert (4);} The following is a gradual analysis*/alert (a); //A function block A is found in the warehouse, so the output function a () {alert (4);}        varA = 1;//found to be an expression modify the value of a in the warehouse by changing the function block to variable a = 1;alert (a);//found in warehouse a = 1 Output 1        functionA () {//line-by-row parsing when a function is just a declaration only an expression can change the value of a variable in the "warehouse"Alert (2);  } alert (a); //Output 1        varA = 3;//the value of a in the warehouse is changed to 3alert (a);//Output 3        functionA () {//similarlyAlert (4);  } alert (a); //Output 3A ();//at this point A is a value, not a function, so an error is</script>

2) Scope problem 1 output result is undefined 1

<script>/*Now the function fn1 is a child of <script>, first pre-parsing (note that at this point the pre-parsing is only for global <script>) the pre-parsed result is a = undefined function fn1 () {alert (a ); var a = 2;}*/        varA = 1;//the A variable in global pre-parsing becomes 1        functionfn1 () {alert (a); //the output undefined can be known by the following pre-resolved results            varA = 2;//the A variable in the function scope becomes 2, which is recycled by the GC after the function execution is completed} fn1 (); //Call the function, enter the scope of the function, first pre-parse, the result of pre-parsing is a = undefinedalert (a);//output Global pre-parsing of A is now 1</script>

3) Scope problem 2 output result is 1 2 1

<script>/*<script> Scope Pre-parse results to a = undefined function fn1 (a) {...}*/        varA = 1; functionFN1 (a) {//at this point A is a parameter parameter and the expression is now equivalent to var a = 1;alert (a);//Output 1            varA = 2;//An expression changes the value of a = 2alert (a);//Output 2, Function end GC Recycle} fn1 (a); /*the pre-parsing result of the function fn1 is a = undefined*/alert (a); //A = 1 in the output <script> domain;</script>

3) * More than one arguments use actually in function parameter a variable A and arguments[0] are the same

<script>/*pre-resolves to a = undefined function fn1 (a) {...}*/        varA = 1;//a = 1;        functionFN1 (a) {//equivalent to var a = 1;Arguments[0] = 3;//equivalent to a = 3;alert (a);//Output Number 3            varA = 2;//a = 2;Alert (arguments[0]);//Output Number 2} fn1 (a); /*pre-parsed to a = undefined*/alert (a);//Output Number 1</script>

4) Scope chain issues

<script>/*<script> The pre-parsed result of the scope is a = undefined function fn1 () {...}*/        varA = 1;//change the value of a to a = 1        functionfn1 () {alert (a); //not found in your own pre-analytic "warehouse" then go to the parent <script> scope of the pre-parsed "warehouse", the results                        //A = 1 is found then the outputA = 2;//change the value of a in parent <script> scope A = 2 Note now that the FN1 "warehouse" is empty, so the GC has nothing to recycle;} fn1 (); /*Pre-parsing when you encounter a variable declaration without var and no function declaration can be considered as the current function of the warehouse is empty*/alert (a); //output A = 2;</script>

Other: So by some content you can know that if you want to get the value inside a function, there are basically two ways

1) Use the scope chain to get the parent variable

    <script>        var  str;         function fn1 () {            var tmp = ' abc ';             = tmp;        }        FN1 ();        alert (str);     </script>

2)

    <script>        function  fn1 () {            var tmp = ' abc ';            FN2 (TMP);        }         function Fn2 (a) {            alert (a);        }        FN1 ();     </script>

Understanding of the scope of JavaScript (i)

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.