[Original] JavaScript Knowledge series-Scope

Source: Internet
Author: User
Execution Environment and scope

Execution context is the most important concept in javascript. The execution environment defines other data that variables or functions have the right to access and determines their respective actions. Each execution environment has a variable object associated with it. All variables and functions defined in the environment are stored in this object. Although the code we wrote cannot access this object, the parser will use it in the background when processing data.

The global execution environment is the most peripheral execution environment. Depending on the host environment where ECMAScript is implemented, the objects in the execution environment are different. In a Web browser, the global execution environment is considered a window object because all global variables and functions are created as properties and methods of the window object. After all the code in an execution environment is executed, the environment is destroyed, all the variables and function definitions stored in them are also destroyed (the Global execution environment knows that the application exits, for example, when the web page is closed or the browser is closed ).

Local execution environment. Each function has its own execution environment. When the execution flow enters a function, the function environment is pushed into an environment stack. After the function is executed, the stack pops up its environment and the control is returned to the previous execution environment. The execution flow in the program is controlled by this convenient mechanism.

When the code is executed in an environment, a scope chain of the variable object is created ). The purpose of the scope chain is to ensure that the execution environment of the team has the right to access all the variables and functions in an orderly manner. The frontend of the scope chain is always a variable object in the environment where the code currently executed is located. If the environment is a function, the activation object is used as the variable object. The activity object contains only one object at the beginning, that is, the arguments object (this object does not exist in the global environment ). The next variable object in the scope chain comes from the include (external) environment, and the next variable object comes from the next include environment, which continues to the global execution environment; variables in the global execution environment are always the last object in the scope chain.

The identifier parsing process searches for the identifier at the level of the scope chain. The search process starts from the front end of the scope chain, and then traces back to the end step by step until the identifier is found.

The essence of a scope chain is a pointer list pointing to a variable object. It only references but does not actually contain the variable object.

Extended scope chain

Although there are only two types of execution environment-global and local, there are other methods to extend the scope chain. This should be because some statements can temporarily Add a variable object to the front end of the scope chain. The variable object will be removed after code execution. In either case. Specifically, when the execution flow enters any of the following statements, the scope chain will be extended:

Catch Block of the Try-catch statement;

With statement

Both statements Add a variable object to the frontend of the scope chain. The with statement adds the specified object to the scope chain. For a catch statement, a new variable object is created, including the declaration of the thrown error object.

Change function Scope

Each function contains two non-inherited methods: apply () and call (). The purpose of these two methods is to call a function in a specific scope, which is actually equal to setting the value of this object in the function body.

Function binding: an increasingly popular technique that can be seen in many plug-ins (jquery and backbone. Function binding creates a function. You can call another function with a specified parameter in a specific this environment. It is often used with callback functions and Event Handlers to keep the code execution environment while passing functions as variables.

ECMAScript 5 defines a native bind () method for all functions, further simplifying the operation.

No block-level scope

JavaScript has no block-level scope. In other C-like languages, code blocks enclosed by curly braces have their own scopes (if ECMAScriptd is used, it is their own execution environment ), therefore, variables can be defined based on conditions.

If (true ){

Var color = 'blue ';

}

For (var I = 0; I <10; I ++ ){

DoSomething (I );

}

The variable declaration in the If for statement adds the variable to the current execution environment. After the for loop is executed, it still exists in the execution environment outside the loop.

Variables declared using var are automatically added to the nearest environment. Within a function, the poorest environment is the local environment of the environment. In the with statement, the closest environment is the function environment. If the var declaration is not used during initialization, the variable is automatically added to the global environment.

Simulate block-level scope

Anonymous functions can be used to simulate block-level scopes. The syntax is as follows:

(Function (){

// Block-level scope

})()

The code above defines and understands that an anonymous function is called. Include the function declaration in a parentheses, indicating that it is actually a function expression. The other parentheses that follow them immediately call this function.

You can understand anonymous functions as follows:

Var someFunction = function (){\

// Block-level scope

};

SomeFunction ();

Define a function and call it immediately. To define a function, create an anonymous function and copy it to the variable someFunction. To call a function, add a pair of parentheses (someFunction () after the function name (). Can I replace the function name directly with the function value here?

Function (){

// Block-level scope

} (); // Error!

This code may cause syntax errors because JavaScript regards the function keyword as the beginning of a function declaration, and the function declaration cannot be followed by parentheses. However, the function expression can be followed by parentheses. To convert a function declaration to a function expression, you only need to give it a pair of parentheses.

(Function (){

// Block-level scope

})();

In actual application, this method can also be used.

! Function (){

}();

Start with the exclamation mark "! "Can also be changed to"; "" +. However, reading is not as easy as reading the above form.

PS: function declaration and function expression

The difference between a function declaration and a function expression is that parsers are not treated equally when loading data to an execution environment. The parser will first read the function declaration and make it accessible before executing any code. This important feature is function declaration elevation (function declaration hoisting). As for function expressions, the parser will be interpreted and executed only when it is executed in its line of code.

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.