About JavaScript scopes and scopes _ basic knowledge

Source: Internet
Author: User
Tags variable scope
This article mainly talks with you about JavaScript scopes and scopes. What are JavaScript scopes and scopes? Interested partners can refer to each programming language, all the variables have a valid range. If the range is exceeded, the variable becomes invalid. This is the scope of the variable. From a mathematical point of view, it is the domain of the independent variable.

The scope is the accessible range of variables, that is, the scope controls the visibility and lifecycle of variables and functions. In JavaScript, objects and functions are also variables. variables are defined inside the declared function bodies and any nested function bodies.

I. Static and Dynamic scopes

Static Scope

It indicates that the declared scope is determined at the compilation of the program body, also known as the lexical scope. Most modern programming languages use static scope rules, which JavaScript uses.
In languages with static scopes, the most nested scope rules are used: the identifiers introduced by a declaration are visible in the scope of the declaration, it is also visible in each scope of its internal nesting, unless it is covered by another declaration of the same name identifier nested inside it.
To find the object referenced by a given identifier, you should look for it in the currently inmost scope. If a declaration is found, the object referenced by the identifier can be found. Otherwise, we will go to the outer scope to look for it, and continue to check the outer scope in an external order until it reaches the outermost nesting level of the program, that is, the scope of the Global Object declaration. If no declaration is found at all levels, this program has an error. As follows:

function cha(){ var name = "xiao;" function chb() { function chc() { console.log(name); } } }

First, the function searches for the definition of name from chb (), then proceeds to the up search layer by layer, and finally finds the definition of name in cha (). If no definition is found, an error is returned.

2. dynamic scope

In a language with dynamic scopes, the objects referenced by a variable in a program are determined according to the control flow information of the program during the runtime.

Ii. JavaScript Scope

JavaScript has two scopes: global and local.

1. Global Scope)

Any position in the Code is defined. Even if a global variable is defined in a nested js code in the html page, the variable can still be accessed in the referenced js file. This may cause global variable pollution.

Variables in the following three cases are regarded as global variables.
(1) functions at the outermost layer and variables at the outermost layer have global scopes.
(2) variables directly assigned without definition are automatically declared as having a global scope.
(3) All properties of the window object have a global scope

2. Local Scope)

Partial scopes can only be accessed in fixed code segments, for example, variables in a function (function scope)

Var name = "xuxiaoping"; function echoName () {var firstname = "xu"; // secondname = "xiao"; // global scope function echoFirstName () {console. log (first name); // xu} console. log (secondname); return echoFirstName;} console. log (name); // global scope var f = echoName (); f (); console. log (firstname); console. log (secondname );

Result:
Xuxiaoping
Xiao
Xu // The inner function can access the variable of the outer function
Undenfined // internal variables of the function that cannot be accessed outside the Function
Xiao

JavaScript attaches the global variable to the window object and becomes the property of the window object.

3. Function Scope

Block-level scope: Any statement set in a pair of curly braces belongs to one block. All variables defined in this block are invisible outside the block. Most C classes have block-level scopes.
However, one important feature of JavaScript is that it does not have block-level scope.

function echoi() { for(var i = 0;i<10;i++){ ;//console.log(i); } if(true){ var str = "hello"; } console.log(i); console.log(str);}echoi();

Output result:

10
Hello

It can be seen that, outside the for statement (or if, while), the variable I defined in the block is still accessible. That is to say, JavaScript does not support block-level scopes. It only supports function scopes, and variables defined anywhere in a function are visible anywhere in the function. As a programmer who learns C and java from the beginning, this is a bit difficult to adapt. The same is true for PHP tests.

Of course, JavaScript closures can be used to simulate block-level scopes.

function echoi() { (function() { for(var i = 0;i<10;i++){ ;//console.log(i); } })(); if(true){ var str = "hello"; } console.log(i); console.log(str);}echoi();

The result is: I undefined.

In this way, the definition of variables is isolated. In js, to prevent name conflicts, we should try to avoid using global variables and global functions. Therefore, this type of closure is especially useful.

4. JavaScript variable Lifecycle

The JavaScript variable lifecycle is initialized when it is declared.
Local variables are destroyed after the function is executed.
Global variables are destroyed after the page is closed.

Iii. JavaScript scope chain

The chain can be combined with the linked list in the data structure.

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:

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:

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:

  

During function execution, every time a variable is encountered, an identifier parsing process is performed 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.

Iv. 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:

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:

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.

V. with changes to the scope chain

The runtime context of each execution is unique. Therefore, multiple calls to the same function will create multiple runtime contexts. when the execution of the function 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:

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, 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.

Summary

1. The scope of a variable is the range in which the variable is valid.
2. The variable scope chain is the set of objects in the created scope.

The above is all the content of this article, and I hope it will help you learn javascript programming.

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.