A deep understanding of JavaScript scopes and scopes

Source: Internet
Author: User

Scope is one of the most important concepts of JavaScript. To learn JavaScript well, you need to understand the working principles of JavaScript scopes and scope chains. This article briefly introduces the JavaScript scope and scope chain, hoping to help you better learn JavaScript.

JavaScript Scope

Any programming language has the concept of scope. Simply put, scope is the accessible scope of variables and functions, that is, scope controls the visibility and lifecycle of variables and functions. In JavaScript, variables have two scopes: global scope and local scope.

1. Global Scope)

Objects that can be accessed anywhere in the Code have a global scope. Generally, the following situations have a global scope:

(1) The outermost function and variables defined outside the outermost function have a global scope. For example:Copy codeThe Code is as follows: var authorName = "mountain edge Creek ";
Function doSomething (){
Var blogName = "Dream sky ";
Function innerSay (){
Alert (blogName );
}
InnerSay ();
}
Alert (authorName); // Hill edge Creek
Alert (blogName); // Script Error
DoSomething (); // dream sky
InnerSay () // Script Error

(2) All variables whose values are directly assigned at the end are automatically declared as having a global scope. For example:Copy codeThe Code is as follows: function doSomething (){
Var authorName = "mountain edge Creek ";
BlogName = "Dream sky ";
Alert (authorName );
}
Alert (blogName); // dream sky
Alert (authorName); // Script Error

The variable blogName has a global scope, and the authorName cannot be accessed outside the function.

(3) All properties of the window object have a global scope

Generally, all built-in properties of the window object have a global scope, such as window. name, window. location, window. top, and so on.

1. Local Scope)

Unlike global scopes, local scopes are generally accessible only within a fixed code segment. The most common is internal functions, in some cases, we can see that some people turn this scope into a function scope. For example, the blogName and innerSay functions in the following code only have a local scope.Copy codeThe Code is as follows: function doSomething (){
Var blogName = "Dream sky ";
Function innerSay (){
Alert (blogName );
}
InnerSay ();
}
Alert (blogName); // Script Error
InnerSay (); // Script Error

Scope Chain)

In JavaScript, functions are also objects. In fact, everything in JavaScript is objects. Function objects, like other objects, have attributes that can be accessed by code and a series of internal attributes that are only accessible by the JavaScript engine. One of the internal properties is [[Scope], defined by the third edition of the ECMA-262 standard, which contains a set of objects in the Scope created by the function, this set is called the function scope chain, which determines which data can be accessed by the function.

After a function is created, its scope chain will be filled with accessible data objects in the scope of the function. For example, define the following function:Copy codeThe Code is as follows: function add (num1, num2 ){
Var sum = num1 + num2;
Return sum;
}

When the function add is created, its scope chain is filled with a global object, which contains all global variables, as shown in (Note: The image only lists part of all variables):

The scope of function add will be used during execution. For example, run the following code: Copy codeThe Code is as follows: var total = add (5, 10 );

When this function is executed, an internal object called "execution context" is created, and the runtime context defines the environment when the function is executed. Each runtime context has its own scope chain for identifier parsing. When the runtime context is created, its Scope chain is initialized to the objects contained in the [[Scope] of the currently running function.

These values are copied to the scope chain of the runtime context in the order they appear in the function. They form a new object called the activation object. this object contains all the local variables, named parameters, parameter sets, and this of the function, this object is then pushed to the front end of the scope chain. When the context is destroyed during the runtime, the activity object is also destroyed. Shows the new scope chain:

When a variable is not encountered during function execution, it will go through an identifier parsing process to determine where to obtain and store data. This process searches for identifiers with the same name from the scope chain header, that is, from the activity object. If the identifiers are found, the variables corresponding to the identifiers are used, if the next object in the scope chain is not found, and if no object is found after the search, the identifier is considered undefined. During function execution, each identifier must undergo such a search process.

Scope chain and code optimization

From the structure of the scope chain, we can see that the deeper the identifier is in the context chain during the runtime, the slower the read/write speed. As shown in, because global variables always exist at the end of the context scope chain at runtime, It is the slowest to search for global variables during identifier parsing. Therefore, when writing code, use global variables as little as possible and use local variables as much as possible. A good rule of thumb is that if a cross-scope object is referenced more than once, it is stored in a local variable before being used. For example, the following code:Copy codeThe Code is as follows: function changeColor (){
Document. getElementById ("btnChange"). onclick = function (){
Document. getElementById ("targetCanvas"). style. backgroundColor = "red ";
};
}

This function references the global variable document twice. To search for this variable, you must traverse the entire scope chain until it can be found in the global object. This code can be rewritten as follows:Copy codeThe Code is as follows: function changeColor (){
Var doc = document;
Doc. getElementById ("btnChange"). onclick = function (){
Doc. getElementById ("targetCanvas"). style. backgroundColor = "red ";
};
}

This code is relatively simple and will not show a huge performance improvement after rewriting. However, if a large number of global variables in the program are repeatedly accessed, the code performance after rewriting will be significantly improved.

Change the scope chain

The runtime context corresponding to each function execution is unique. Therefore, multiple calls to the same function will create multiple runtime contexts. When the function execution is complete, the execution context will be destroyed. Context is associated with a scope chain during each runtime. In general, the scope chain will only be affected by the with statement and catch statement during the context running at runtime.

The with statement is a quick application of objects to avoid repeated code writing. For example:Copy codeThe Code is as follows: function initUI (){
With (document ){
Var bd = body,
Links = getElementsByTagName (""),
I = 0,
Len = links. length;
While (I <len ){
Update (links [I ++]);
}
GetElementById ("btnInit"). onclick = function (){
DoSomething ();
};
}
}

Here, we use the width statement to avoid writing documents multiple times, which looks more efficient and actually produces performance problems.

When the code runs to the with statement, the scope chain of the context in the runtime is changed temporarily. A new variable object is created, which contains all the attributes of the object specified by the parameter. This object will be pushed to the header of the scope chain, which means that all the local variables of the function are now in the second scope chain object, so the access cost is higher. As shown in:

Therefore, you should avoid using the with statement in the program. In this example, you can simply store the document in a local variable to improve the performance.

The other one that will change the scope chain is the catch statement in the try-catch statement. When an error occurs in the try code block, the execution will jump to the catch statement, and then push the exception object into a mutable object and place it in the scope header. Within the catch code block, all local variables of the function will be placed in the second scope chain object. Sample Code:Copy codeThe Code is as follows: try {
DoSomething ();
} Catch (ex ){
Alert (ex. message); // The scope chain changes here
}

Note that once the catch statement is executed, the scope chain will return to the previous status. Try-catch statements are useful in code debugging and exception handling, so we do not recommend that you avoid them completely. You can optimize the code to reduce the impact of catch statements on performance. A good mode is to delegate errors to a function for processing, for example:Copy codeThe Code is as follows: try {
DoSomething ();
} Catch (ex ){
HandleError (ex); // Delegate to the processor Method
}

The optimized code. The handleError method is the only code executed in the catch clause. This function receives exception objects as parameters so that you can handle errors more flexibly and uniformly. Since only one statement is executed without local variable access, temporary changes to the scope chain will not affect code performance.

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.