Syntax scopes and lexical scopes (turn)

Source: Internet
Author: User
Tags define local script tag

var ClassA = function () {this. Prop1 = 1;} classa. Prototype.             func1 = function () {var = this, var1 = 2;             function A () {return function () {alert (VAR1);         Alert (this. prop1); } .     Apply (that);     } ; A (); var obja = new ClassA (); Obja. Func1 ();

You should write the above code like this, in fact, I want to express here is sometimes a method to define the place and the use of the place will be 108,000 miles apart, that method executes, it can access which variables, can not access which variables, how to judge this. This is the problem we need to analyze this time-lexical scopes

Lexical scopes: The scope of a variable is determined when it is defined, not when it is executed, that is, the lexical scope depends on the source code, which can be determined by static analysis, so the lexical scope is also called a static scope. With and Eval excepted, so can only say JS scope mechanism is very close to the lexical scope (lexical scope).

Below, through a few small cases, began to understand the lexical scope and closure of the necessary, JS implementation of some of the underlying concepts and theoretical knowledge. Recurrence of the classic case list     1, a classic case a /* Global (Window) field under a section of code/function A (i) {var i; alert (i); } ; A (10);

Question: What does the above code output?
Answer: Yes, just pop 10. The specific implementation process should be such a function has a formal parameter I, call a function when the argument 10, the formal parameter i=10 then define a local variable with the same name I, not assigned alert output 10 think: local variable i and formal parameter I are the same storage space.     2. The classic case two /* A section of code under the Global (window) field */function A (i) {alert (i); alert (arguments [0]);     Arguments[0] should be the formal parameter i var i = 2;     alert (i); alert (arguments [0]); } ; A (10);

Question: What does the above code output? ((10,10,2,10 | | 10,10,2,2))
Answer: The result of the run in Firebug is the second 10,10,2,2, guess right ..., the following is a brief introduction to the implementation process a function has a formal parameter I, when the A function is invoked to pass the argument 10, the formal parameter i=10 the first alert to output the value 10 of the parameter I to the second alert Arguments[0] output, which should also be I then define a local variable I and assign a value of 2, when the local variable i=2 the third alert, the value 2 of the local variable I outputs the fourth alert again, the output of the arguments[0] is considered: Here is a description of the local variable Do I have the same value as the formal parameter I?     3. Classic cases Three /* A section of code under the Global (window) field */function A (i) {var i = i; alert (i); } ; A (10);

Question: What does the above code output? ((undefined | | 10))
Answer: The result of the operation in Firebug is 10, the following is a brief statement of the implementation process the first sentence declares a local variable i with the same name as the formal parameter I, and according to the result we know that the latter I is pointing to the formal parameter I, so here is equal to the value 10 of the parameter I to the local variable i second alert Of course output 10 thinking: Combined with the case column two, here basically can explain the local variable i and parameter I point to the same storage address. 4, the classic case four /* Global (Window) field under a section of code/var i = 10;     function A () {alert (i);     var i = 2; alert (i); } ; A ();

Question: What does the above code output? Boy, look, it's not going to kill you. Wow haha, don't give you the option)
Answer: In the Firebug run result is undefined, 2, the following simple implementation process first alert output undefined second alert Output 2 think: what is going on. 5, the classic case of five ...... N

See a few examples above, you may think, how can I write JS for several years, how such a simple example will hesitate, the result may also be wrong. The reason may be: we can quickly write a method, but in the end how the internal implementation of the method. What about the details of the execution? You may not have had a thorough study and understanding. To understand these details, you need to understand the way the JS engine works, so we will be the JS engine to a method of parsing process a little more in-depth introduction of the parsing process

1, the implementation of sequential compiled language, compilation steps are divided into: lexical analysis, syntax analysis, semantic check, code optimization and byte generation. interpreted language, through lexical analysis and syntactic analysis of the parse tree, you can begin to explain the implementation. Here is a simple primitive about the principle of parsing process, only as a reference, the detailed parsing process (various JS engine and different) still need a further study

The JavaScript execution process, if a document flow contains more than one script snippet (JS code separated by a script tag or a JS file that is introduced), the sequence of operations is: Step 1. Read the first code snippet (the JS execution engine does not execute the program one line at a time, but a section of analysis performed) Step 2. Do lexical analysis and grammar analysis, mistakes are reported grammatical errors (such as parentheses do not match, etc.), and jump to step 5 step 3. Do "pre-resolution" for "VAR" and "function" Definitions (never error, because only correct declarations are parsed) step 4. Execute code snippet, error (such as variable undefined) step 5. If you have the next code snippet, read the next code snippet and repeat step 2 step 6. End

2, the special description
Global Domain (window) field All JS code can be considered an "anonymous method", it will be automatically executed, and this "anonymous method" in the other method is to be displayed when the call is performed
3, critical steps
The above process, we are mainly divided into two stages of parsing: is through the syntax analysis and pre-analysis of the construction of a valid parsing tree. Execution: Executing a specific FUNCTION,JS engine when executing each instance of a function, an execution environment (EXECUTIONCONTEXT) and active objects (Activeobject) are created (they belong to the host object, consistent with the life cycle of the function instance)

3. Key Concepts
Here, we put more emphasis on the following concepts, these concepts will be shown below with a single entity, easy to understand the syntax analysis Tree (SYNTAXTREE) can visually express the relevant information of this Code, the specific implementation of the JS engine to create a number of tables, Used to record the set of variables (variables) Within each method, the method set (functions) and the scope (scope), such as the execution Environment (ExecutionContext), can be understood as an object that records the "external description" of the currently executing method, recording the type of method being executed , the name, parameter, and active object (Activeobject) Activity Object (Activeobject) is understood as an object that records the currently executing method "Internal execution information," which records internal variable sets (variables), inline function sets (functions), The required information for execution of an argument (arguments), scope chain (Scopechain), in which the internal set of variables (variables), the inline function sets (functions) are copied directly from the parsing tree that was established in the first step. Lexical scopes: The scope of a variable is determined when it is defined, not when it is executed, that is, the lexical scope depends on the source code, which can be determined by static analysis, so the lexical scope is also called a static scope. With and Eval excepted, so you can only say the scope mechanism of JS is very close to the lexical scope (lexical scope) scope chain: The implementation mechanism of the lexical scope is the scope chain (Scopechain). A scope chain is a mechanism for searching by name (name lookup), first looking in the activeobject of the current execution environment, not found, then searching through the scope chain to the parent Activeobject to find the global calling object

4. Entity Representation
Analytic Simulation

It's pretty hazy to see here, I guess. What is the parsing tree, what is the parsing tree, what is the scope chain, how do we do it, what is the activity object, and so on, or not too clearly, we will simulate the whole parsing process through a piece of actual code, we will parse the tree, The active object is actually created to understand the scope and how the scope chain is implemented.
1. Analog Code/* Global (Window) field under a piece of code/var i = 1, j = 2, k = 3;         function A (O, p, x, q) {var x = 4;     alert (i);             Function B (r, s) {var i = one, y = 5;         alert (i);                 function C (t) {var z = 6;         alert (i);             } ;             expression var d = function () {alert (y);             } ;             C (60);     D ();         } ; B (40, 50); } A (10, 20, 30);

2. Syntax Analysis Tree
The above code is very simple, that is, the first definition of some global variables and global methods, then in the method to define local variables and local methods, now the JS interpreter read this code to start parsing, the preceding mentioned JS engine will first through the grammar analysis and pre-resolution to get the syntax analysis tree, as for the syntax analysis tree long what kind of, Have some information, below we have a simple structure: a JS object (in order to clearly represent the various objects of the reference relationship, here is only pseudo object representation, may not be able to run) to describe the syntax analysis tree (which we are familiar with, the actual structure we do not go into the study, it must be more complex, This is to help understand the parsing process and deliberately simplify it./** * Simulate a parse tree, store variables and methods within function * * var   syntaxtree = {       //Global object in language Representations     windows in the parse tree: {        variables: {            I: {  Value:1},             J: {  Value:2},         &N Bsp   K: {  Value:3}        },         functions: {    &N Bsp       A:This. A        }    },       A: {        variables: {&NB Sp           x: ' undefined '        ,         functions : {           B:this. b        },         Scope:this. Windows    },       B: {        variables: { ,           y: ' undefined '        },         functions: {    &N Bsp       C:this. C,             D:this. D        },         Scope:this. A    },       C: {        variables: {        &NBSP ;   Z: ' undefined '        },         functions: {},         Scope:this. b    },       D: {        variables: {},         FU Nctions: {},         scope: {    &NBSP      Myname:d,            scope:this. b        }    }};

The above is a simple representation of the parse tree, as we analyzed earlier, where the parse tree mainly records the set of variables (variables) in each function, the method set (functions), and scope (scope)
Parsing tree key point 1 variable set (variables), only variable definition, there is no variable value, this time the variable value of all the "undefined" 2 scope (scope), according to the lexical scope of the characteristics of the scope of each variable is already clear, It does not change with the environment at execution. "What does that mean?" Is that we often return a method and then execute it in another method, in which the variables in the method are scoped by the scope of the method definition. In fact, the idea here is that no matter how complicated you are, how far it is to execute this method, and ultimately determine whether the variable can be accessed in the method or where the method definition is to be verified. 3 scope (scope) Establish rule A for function declarations and anonymous function expressions, [scope] is the scope B for the function expression when it was created, [scope] The top is a new JS object (that is, inherited Object.prototype), this object has two attributes, the first is its own name, the second is the scope of the definition, the first function name is to ensure that the code inside the function can access its own function name for recursion.

3, the implementation of the environment and activities of the object
Parsing complete, start executing code. When we call each method, the JS engine automatically creates an execution environment and an active object that is consistent with the lifecycle of the method instance, provides the necessary execution support for the method execution, and, for several of the above methods, We have set up the active object here (in the sense that the active object is generated when the method is executed, and for the sake of demonstration, the active object of all methods is defined here), as follows:
Execution Environment /** * Execution Environment: execution environment created at function execution * * var   executioncontext = {    window: {        type: ' Global ',         Name: ' Global ',       body:activeobject  . Windows    },       A: {        type: ' function ',         Name: ' A ',         Body:activeobject. A,         Scopechain:this. window. Body    },       B: {        type: ' function ',       & nbsp Name: ' B ',         Body:activeobject. B,         Scopechain:this. A. Body    },       C: {        type: ' function ',       & nbsp Name: ' C ',         Body:activeobject. C,         Scopechain:this. B. Body   &NBSp }       D: {        type: ' function ',         name: ' d ' ,         Body:activeobject. D,         Scopechain:this. B. Body    }}

The execution environment for each of the above methods stores information such as the type (function) of the method, the method name (FuncName), the active object (activeobject), the scope chain (Scopechain), and the key points are as follows: the Body property, Directly to the active object Scopechain attribute of the current method, the scope chain, which is a list structure, which points to the active object (Activceobject) of the method corresponding to the scope, according to the scope attribute of the current method in the parsing tree. Variable lookup is to follow this chain to find

Active Object /** * Active object: List of active objects created when function executes * * var   activeobject = {        window: {      &NBS P Variables: {            I: {  value:1},           &NBS P J: {  Value:2},             K: {  Value:3}         },         functions: {            A:This. A        }    },       A: {        variables: {      &NBSP ;     x: {value:4}        },         functions: {    &N Bsp       B:syntaxtree. b        },         parameters: {     ,       o: {value:10},             p: {value:20},            X:this. Variables. X,             Q: ' undefined '        },       &NBSP ; Arguments: [this. parameters. O, this. Parameters P, this. parameters. x]    },     &NBS P B: {        variables: {            y: {  Value:5}        },         functions: {            C:syntaxtre E. C,             D:syntaxtree. D        },         parameters: {       -    R: {value:40},             s: {value:50}        },   &nbs P     arguments: [this. parameters. R, this. Parameters. S]    },       C: {& nbsp      variables: {            Z: {  Value:6}        }, &N Bsp       functions: {},         parameters: {            U: {value:70}        },         arguments: [this. parameters. U] &nbs P  },       D: {        variables: {},         functions: {},         parameters: {},         arguments

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.