Lexical scopes of javascript

Source: Internet
Author: User

You should have written a similar code. In fact, what I want to express here is that sometimes a method definition is 108,000 different from that used. When the method is executed, what variables can be accessed and what variables cannot be accessed? How can this problem be determined? This is the problem we need to analyze this time -- lexical scope bkjia.com

var classA = function(){    this.prop1 = 1;}classA.prototype.func1 = function(){    var that = this,        var1 = 2;     function a(){        return function(){            alert(var1);            alert(this.prop1);        }.apply(that);    };    a();}var objA = new ClassA();objA.func1(); 

liehuo.net

Lexical scope: the scope of a variable is determined during definition rather than execution. That is to say, the lexical scope depends on the source code and can be determined through static analysis. Therefore, the lexical scope is also called static scope. Except with and eval, we can only say that the JS scope mechanism is very close to the Lexical scope ). Lie-fire-network

The following are a few small cases to get an in-depth understanding of lexical scopes and closures. Some Concepts and theoretical knowledge at the underlying layer during Javascript execution. Strong/fire/Network

Classic case column reproduction 1. Classic Case 1
/* Code in the global (window) Field */function a (I) {var I; alert (I) ;}; a (10 );

Veryhuo.com

Q: What will the above Code output?
Answer: Yes, 10 is displayed. The specific execution process should be like this liehuo.net

Function a has an I parameter. When function a is called, input 10 arguments. The I parameter is 10.
Next, define a local variable I with the same name without assigning a value.
Alert outputs 10 Fire Network

Thinking: is the local variable I and the shape parameter I the same bucket? Veryhuo.com

2. Classic Case 2
/* Code in the global (window) Field */function a (I) {alert (I); alert (arguments [0]); // arguments [0] should be the form parameter I var I = 2; alert (I); alert (arguments [0]) ;}; a (10); veryhuo.com

Q: What will the above Code output? (, | ))
Answer: The running result in FireBug is the second 10, 10, 2, 2, right... The following describes the specific execution process.

Bkjia.com

Function a has an I parameter. When function a is called, input 10 arguments. The I parameter is 10.
The first alert outputs the value of I 10.
The second alert outputs arguments [0], which should also be I
Then define a local variable I and assign it to 2. At this time, the local variable I = 2
The third alert outputs the value 2 of the local variable I.
The fourth alert output arguments [0] again to liehuo.net

Thinking: Can the local variable I and the parameter I have the same value? Liehuo.net

3. Typical Case 3
/* A piece of code in the global (window) Field */function a (I) {var I = I; alert (I) ;}; a (10); Fire Network

Q: What will the above Code output? (Undefined | 10 ))
Answer: The running result in FireBug is 10. The following describes the specific execution process veryhuo.com.

The first clause declares a local variable with the same name as the form parameter I. According to the result, we know that the next I point
This is equivalent to assigning the value 10 of the parameter I to the local variable I.
The second alert will certainly output 10 liehuo.net

Thinking: Combined with Case 2, here we can basically show that the local variable I and the form parameter I point to the same storage address! Liehuo.net

4. Typical Case 4
/* Code segment in the global (window) Field */var I = 10; function a () {alert (I); var I = 2; alert (I );}; a (); liehuo.net

Q: What will the above Code output? (Boy, you're not dead this time! Wow Haha, I will not give you the option)
Answer: The running result in FireBug is undefined, 2. The following describes the specific execution process veryhuo.com.

The first alert outputs undefined
The second alert outputs 2 liehuo.net

Think: What's the problem?

Liehuo.net

5. Typical Case 5 .............. N

When you see the above examples, you may think about how it is possible that I have written JavaScript for a few years, and I will hesitate to give such a simple example, and the result may be wrong. In fact, the possible reason is: we can quickly write a method, but in the end, how is the internal implementation of the method? What are the execution details? You may not have any in-depth study or understanding. To understand these details, we need to understand how the JS engine works. So next we will introduce the parsing process of a method by the JS engine in a little more depth. liehuo.net

Code parsing process 1. javascript execution sequence

The compilation steps include lexical analysis, syntax analysis, semantic check, code optimization, and byte generation.
After obtaining the syntax analysis tree through lexical analysis and syntax analysis, the interpreted language can start to be executed. Here is a simple and original principle of the parsing process. It is only for reference. The detailed parsing process (different JS engines) also requires further research.
JavaScript execution. If a Document Stream contains multiple script code segments (JavaScript code separated by the script tag or the introduced js file), the execution sequence is bkjia.com.

  1. Read the first code segment (the js execution engine does not execute the program one by one, but analyzes and executes the program one by one)
  2. Perform lexical analysis and syntax analysis. If there is a mistake, a syntax error is reported (for example, parentheses do not match), and jump to Step 5.
  3. Perform "pre-resolution" on the [var] variable and [function] definition (no error will be reported, because only the correct declaration is parsed)
  4. Run the code segment. If the code segment is incorrect, an error is returned (for example, the variable is not defined)
  5. If there is another code segment, read the next code segment and repeat Step 2.
  6. End
2. Special Instructions

All JS code in the window field can be regarded as an "anonymous method" and will be automatically executed, other methods in this "anonymous method" are executed only when they are displayed and called.

3. Key Steps

The above process is divided into two phases: liehuo.net

Javascript parsing: A Legal syntax analysis tree is constructed through syntax analysis and pre-parsing.
Javascript Execution: When executing a specific function, the JS engine creates an execution environment (ExecutionContext) and activity object (activeObject) when executing each function instance (they belong to the Host object, is consistent with the life cycle of the function instance)

Liehuo.net

3. Key Concepts

Here, we will emphasize the following concepts, which will be represented by one entity below for your understanding.

Helping customers

SyntaxTree: displays information about the code. The JS engine creates tables, used to record the variables, functions, and scope in each method.

Veryhuo.com

Execution Environment (ExecutionContext): it can be understood as an object that records the current execution method [external description information], record the type, name, parameters, and activity object (activeObject) of the method to be executed ).

Strong & fire & Network

Activity object: it can be understood as an object that records the current execution method [internal execution information], recording the internal variable set (variables), embedded function set (functions), real parameters (arguments), scope chain (scopeChain) and other required information for execution, including the internal variable set (variables), nested function set (functions) the syntax analysis tree created in step 1 is copied directly. Veryhuo.com

Lexical scope: the scope of a variable is determined during definition rather than execution. That is to say, the lexical scope depends on the source code and can be determined through static analysis. Therefore, the lexical scope is also called static scope. Except with and eval, we can only say that the JS scope mechanism is very close to the Lexical scope ). Liehuo.net

Scope chain: the implementation mechanism of lexical scopes is scopeChain ). The scope chain is a set of Name Lookup mechanisms. First, it is searched in the ActiveObject of the current execution environment. If it is not found, it is searched in the parent ActiveObject along the scope chain, always find the Global Object ).

Veryhuo.com

4. entity representation javascript parsing Simulation

It is estimated that everyone is still confused here. What is the syntax analysis tree? What is the syntax analysis tree like? How is the scope chain implemented? What is the content of the activity object, still not very clear. Next we will simulate the entire parsing process through a piece of actual code. We will create the syntax analysis tree and activity objects to understand the scope, how is the scope chain implemented?

1. Simulate code
/* Code segment in the global (window) Field */var I = 1, j = 2, k = 3; function a (o, p, x, q) {var x = 4; alert (I); function B (r, s) {var I = 11, y = 5; alert (I); function c (t) {var z = 6; alert (I) ;}; // function expression var d = function () {alert (y) ;}; c (60 ); d () ;}; B () ;}a (, 30); strong # fire # Network
2. syntax analysis tree

The above code is very simple, that is, some global variables and global methods are defined first, and then local variables and local methods are defined in the method. Now the JS interpreter reads this code and starts parsing, as mentioned above, the JS engine will first obtain the syntax analysis tree through syntax analysis and pre-resolution. As for what the syntax analysis tree looks like, there will be some information. Veryhuo.com

Below we use a simple structure: a JS object (to clearly express the reference relationship between various objects, Here we only represent pseudo objects and may not be able to run) to describe the syntax analysis tree (this is something we are familiar with. We should not go into the actual structure, but it must be much more complicated. Here we want to simplify the parsing process to help you understand it ). Fire net

/*** Simulate the creation of a syntax analysis tree and store the variables and methods in the function */var SyntaxTree ={// the global object in the syntax analysis tree represents window: {variables: {I: {value: 1}, j: {value: 2}, k: {value: 3 }}, functions: {a: this. a }}, a: {variables: {x: 'undefined'}, functions: {B: this. b}, scope: this. window}, B: {variables: {y: 'undefined'}, functions: {c: this. c, d: this. d}, scope: this. a}, c: {variables: {z: 'undefined'}, functions :{}, scope: this. b}, d: {variables :{}, functions :{}, scope: {myname: d, scope: this. B }}; liehuo.net

The above is a simple representation of the syntax analysis tree. As we analyzed earlier, the syntax analysis tree mainly records the variables and functions in each function) and scope ). Veryhuo.com

For more information, click the next page!

  • 2 pages in total:
  • Previous Page
  • 1
  • 2
  • Next Page

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.