JavaScript scope chain

Source: Internet
Author: User

Scope : Scope is the accessible scope of variables and functions, that is, scope controls the visibility and life cycle of variables and functions. In JavaScript, the scope of variables has global scope and local scope two, the scope of the program logic to improve the locality, enhance the reliability of the program, reduce the name of the conflict.

Global scope: objects that can be accessed anywhere in the code have global scope, in JavaScript the global scope is divided into,1) the outermost function and the variables defined outside the outermost function have global scope;2 All variables that do not have a direct assignment defined are automatically declared as having global scope;3) all properties of the Window object have global scope.

Local scope: A variable that is accessible only within a fixed code fragment has a scope of local scope, most commonly a variable declared inside a function

scope chain:in JavaScript , everything is an object. function objects, like other objects, have properties that can be accessed through code and a series of internal properties that are accessible only by the JavaScript engine. One of the internal properties is scope, including a collection of objects in the scope in which the function is created, called the function's scope chain, which determines which data can be accessed by the function. When a function is created, its scope chain is populated with data objects that can be accessed by creating the scope of this function. eg:

function MySum (num1,num2) {

var he=num1+num2;

return he;

}

when MySum is created, it fills a global object in its scope chain, which contains all the global variables, as shown in

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/4B/C7/wKioL1QzSCbzs9rtAACeeKdEgs0960.jpg "title=" 1.png " alt= "Wkiol1qzscbzs9rtaaceekdegs0960.jpg"/>

The corresponding display in the browser is:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/4B/C7/wKioL1QzR6fAciX4AADoWW-aR6U824.jpg "title=" 1 (2). PNG "style=" Float:none; "alt=" wkiol1qzr6facix4aadoww-ar6u824.jpg "/>

The scope of the function mysum will be used when executing (called).

When this function is executed, an internal object called the runtime context is created, and the runtime context defines the environment at which the function executes. Each run-time context uses its own scope chain, used for identifier resolution, when the run-time context is created, and its scope chain is initialized to the object contained in the scope of the currently running function.

These values are copied into the scope chain of the run-time context, in the order in which they appear in the function. Together they form a new object called the "active object", which contains all the local variables of the function, the named arguments, the Parameters collection , andthis, and then the object is pushed into the front of the scope chain, and the active object is destroyed when the run-time context is destroyed. The new scope chain is shown

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/4B/C5/wKiom1QzR3HAiU5qAAFtIslLReM646.jpg "title=" 1 (3). PNG "style=" Float:none; "alt=" wkiom1qzr3haiu5qaaftisllrem646.jpg "/>

During the execution of a function, each time a variable is encountered, it undergoes an identifier parsing process to determine where to get and store the data. The process from the scope chain head, that is, starting from the active object search, find an identifier of the same name, if found to use this identifier corresponding to the variable, if not found to continue to search the scope chain of the next object, if the search all the objects are not found, the identifier is considered undefined. Each identifier undergoes such a search process during the execution of the function.

From the scope structure, you can see that in the scope of the run-time context, the deeper the identifier is, the slower the read and write speed will be. As shown, because global variables always exist at the end of the run-time context scope, finding global variables is the slowest when identifiers are resolved. So when writing code, use as few global variables as possible and use local variables as much as you can. A good rule of thumb is if a cross-scope object is referenced more than once, it is stored in a local variable before it is used.

Effect of scope chain on performance

The runtime context is unique for each execution of a function, so calling a function multiple times results in creating multiple run-time contexts and executing the context destroy when the function finishes executing. Each run-time context is associated with a scope chain. In general, the scope chain is only affected by the WITH statement and catch statement during the run-time context .

The WITH statement is a quick way to apply the image to repeat the code. For example

function Initui () {

With (document) {

var bd=body,

Links=getelementsbytagname ("a"),

I=0,

Len=links.length;

while (I < Len) {

Update (links[i++]);

}

getElementById ("Btninit"). Onclick=function () {

DoSomething ();

};

}

}

here with the statement to avoid writing the document multiple times , it looks more efficient and actually produces performance problems.

The scope chain of the run-time context is temporarily changed when the current code executes to the WITH statement. A new Mutable object is created that contains all the properties of the object specified by the parameter. This object will be pushed into the head of the scope chain, which means that all local variables of the function are now in the second scope chain object, so the access cost is higher. :

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/4B/C5/wKiom1QzSFuz2b__AAINRwZdO54923.jpg "title=" 2.jpg " alt= "Wkiom1qzsfuz2b__aainrwzdo54923.jpg"/>

Therefore, you should avoid using the WITH statement in your program, which in this case can improve performance as long as the document is stored in a temporary variable.

another change in the scope chain is The catch statement in the Try-chatch statement . when an error occurs in the try code, the execution jumps to the catch statement, then pushes the exception object into a Mutable object and puts it in the scope's head. inside the catch code block, all local variables of the function are placed in the second scope object, with the following instance code:

try{

DoSomething ();

}catch (ex) {

alert (ex.message); The scope chain changes here

}

Please note that once Catch after the statement executes, the scope chain opportunity returns to the previous state. Try-catch statements are useful in code debugging and exception handling, so it is not recommended to avoid them altogether. You can reduce The performance impact of catch statements by optimizing your code. A good pattern is to delegate the error to a function handler, for example:

try{

DoSomething ();

}catch (ex) {

HandleError (ex); delegate to processor method

}

after the optimized code,the HandleError method is the only code executed in the Catch clause. The function receives the exception object as a parameter, so that you can handle the error more flexibly and uniformly, because only one statement is executed and there is no access to the local variable, and the temporary change of the scope chain does not affect the performance of the code.


This article is from "Tiger Brother's Blog" blog, please be sure to keep this source http://7613577.blog.51cto.com/7603577/1560922

JavaScript scope chain

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.