JS scope and scope chain details, js scope details

Source: Internet
Author: User

JS scope and scope chain details, js scope details

(1) Scope

The scope of a variable is the region of the variable defined in the program source code.

1. lexical scope is used in JS)

Variables not declared in any function (if var is omitted in the function, it is also regarded as global)

A variable declared in a function has a function scope and is a local variable.

The priority of local variables is higher than that of global variables.

Copy codeThe Code is as follows:
Var name = "one ";
Function test (){
Var name = "two ";
Console. log (name); // two
}
Test ();

If var is omitted in the function, the global variable is affected because it has actually been overwritten as a global variable.

Copy codeThe Code is as follows:
Var name = "one ";
Function test (){
Name = "two ";
}
Test ();
Console. log (name); // two

Function scope, that is, a function is the basic unit of a scope. js does not have block-level scope like c/c ++, such as if.

Copy codeThe Code is as follows:
Function test (){
For (var I = 0; I <10; I ++ ){
If (I = 5 ){
Var name = "one ";
}
}
Console. log (name); // one
}
Test (); // because it is a function-level scope, you can access name = "one"

Of course, higher-order functions are also used in js, which can be understood as nested functions.

Copy codeThe Code is as follows:
Function test1 (){
Var name = "one ";
Return function (){
Console. log (name );
}
}
Test1 ()();

After test1 (), the outer function is called, an inner function is returned, and then () is continued, the inner function is called and executed accordingly, so "one" is output"

Nested functions involve closures, which will be discussed later. Here, the inner function can access the variable name declared in the outer function, which involves the scope chain mechanism.

2. Advance the Declaration in JS

The function scope in js indicates that all variables declared in the function are always visible in the function body. In addition, variables can be used before they are declared. This situation is called hoisting)

Tip: the Declaration is carried out in advance during the js engine pre-compilation, and the declaration has been made before the code is executed.

For example

Copy codeThe Code is as follows:
Var name = "one ";
Function test (){
Console. log (name); // undefined
Var name = "two ";
Console. log (name); // two
}
Test ();

The above shows the following results.

Copy codeThe Code is as follows:
Var name = "one ";
Function test (){
Var name;
Console. log (name); // undefined
Name = "two ";
Console. log (name); // two
}
Test ();

Try again to remove var? This is because the name in the function has been changed to a global variable, so it is no longer undefined.

Copy codeThe Code is as follows:
Var name = "one ";
Function test (){
Console. log (name); // one
Name = "two ";
Console. log (name); // two
}
Test ();

3. It is worth noting that none of the above mentioned parameters are passed. What if test has parameters?

Copy codeThe Code is as follows:
Function test (name ){
Console. log (name); // one
Name = "two ";
Console. log (name); // two
}
Var name = "one ";
Test (name );
Console. log (name); // one

As mentioned before, the basic type is passed by value, so the name passed into test is actually a copy, and the copy is cleared after the function returns.
Do not change the global name for name = "two" in the function, because they are two independent names.

(2) Scope chain

The advanced functions mentioned above involve the scope chain.

Copy codeThe Code is as follows:
Function test1 (){
Var name = "one ";
Return function (){
Console. log (name );
}
}
Test1 ()();

1. Introduce a large paragraph to explain:
Each js Code (Global Code or function) has a scope chain associated with it ).

This scope chain is a list of objects or a linked list. This group of objects defines the variables in the "scope" in this Code.

When js needs to find the value of variable x (this process is called variable resolution), it will start searching from the first object of the chain, if this object has an attribute named x, the value of this attribute is directly used. If the first object does not have an attribute named x, js will continue to search for the next object in the chain. If the second object still does not have the property named x, the next object will be searched, and so on. If no object in the scope chain contains attribute x, the Code does not have x in the scope chain, and a reference error (ReferenceError) is thrown.

2. Example of scope chain:

In the top-level JavaScript code (that is, the Code does not include any function definition), the scope chain is composed of a global object.

In a function that does not contain nesting, there are two objects in the scope chain. The first is the object that defines function parameters and local variables, and the second is the global object.

In a nested function, there are at least three objects in the scope.

3. Create a scope chain rule:

When defining a function (note that it starts when it is defined), it actually saves a scope chain.

When this function is called, it creates a new object to store its parameters or local variables, and adds the object to the scope chain, at the same time, create a new longer "chain" that represents the function call scope ".

For nested functions, the situation has changed: each time an external function is called, the internal function is redefined. Because each time an external function is called, The scope chain is different. Each time an internal function is defined, it requires a subtle difference-the code of the internal function is the same each time an external function is called, And the scope chain associated with this code is also different.

(Tip: I understand the above three points. Remember, I 'd better say it in my own words, or I will stick it back, because the interviewer will ask you directly: Please describe the scope chain ...)

A practical example of the scope chain is as follows:

Copy codeThe Code is as follows:
Var name = "one ";
Function test (){
Var name = "two ";
Function test1 (){
Var name = "three ";
Console. log (name); // three
}
Function test2 (){
Console. log (name); // two
}
Test1 ();
Test2 ();
}
Test ();

The above is a nested function, which corresponds to three objects in the scope chain.
In this case, you need to find the value of name in the scope chain.

When test1 () is successfully called, the sequence is test1 ()-> test ()-> Global Object window because the value of name three is found on test1, so return after completing the search

When test1 () is successfully called, the sequence is test2 ()-> test ()-> Global Object window because the name value is not found on test2, so find the two value of name in test (), and then complete the search and return.

Another example is that sometimes we make mistakes and often get cheated during interviews.

Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Script type = "text/javascript">
Function buttonInit (){
For (var I = 1; I <4; I ++ ){
Var B = document. getElementById ("button" + I );
B. addEventListener ("click", function (){
Alert ("Button" + I); // both are Button4
}, False );
}
}
Window. onload = buttonInit;
</Script>
</Head>
<Body>
<Button id = "button1"> Button1 </button>
<Button id = "button2"> Button2 </button>
<Button id = "button3"> Button3 </button>
</Body>
</Html>

Why?
Search rules based on variables in the scope chain:

Copy codeThe Code is as follows:
B. addEventListener ("click", function (){
Alert ("Button" + I );
}, False );

Here is a function, which is an anonymous function. Since it is a function, it has an object in the scope chain. This function uses variable I, it will naturally look for it in scope.
The search order is the anonymous function --> external function buttonInit () --> Global Object window

I cannot be found in the anonymous function. Naturally, I ran to buttonInit (), OK, and found in,

At this time, the registration event is over. Don't think it will put down I one by one, because the variables within the function scope are always visible to the scope, that is, they will be kept to the final state.

When an anonymous function uses I, the registration event is complete and I has changed to 4, so all of them are Button4.

How can this problem be solved?

Pass the value in it. In each loop, an anonymous function is used to pass the I in for. The rules of anonymous functions are as follows:

Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Script type = "text/javascript">
Function buttonInit (){
For (var I = 1; I <4; I ++ ){
(Function (data_ I ){
Var B = document. getElementById ("button" + data_ I );
B. addEventListener ("click", function (){
Alert ("Button" + data_ I );
}, False );
}) (I );
}
}
Window. onload = buttonInit;
</Script>
</Head>
<Body>
<Button id = "button1"> Button1 </button>
<Button id = "button2"> Button2 </button>
<Button id = "button3"> Button3 </button>
</Body>
</Html>

In this way, you can use Button1. .. 2 .. 3.

4. The above is the basic description of the scope chain. In addition, the with statement can be used to temporarily expand the scope chain (with is not recommended)

Syntax format:

With (object)

Statement

This with statement adds the object to the header of the scope chain, executes statement, and finally restores the scope chain to the original state.

Simple usage:

For example, assign a value to each item in the form.

We can do this directly.

Copy codeThe Code is as follows:
Var f = document. forms [0];
F. name. value = "";
F. age. value = "";
F. email. value = "";

After introducing with (because using with will cause a series of problems, use the above form)

Copy codeThe Code is as follows:
With (document. forms [0]) {
F. name. value = "";
F. age. value = "";
F. email. value = "";
}

In addition, if an object o has the x attribute, o. x = 1;
Use

Copy codeThe Code is as follows:
With (o ){
X = 2;
}

It can be converted to o. x = 2;
If o does not define the attribute x, its function is equivalent to x = 2; a global variable.

Because with provides a shortcut for reading the properties of o, it cannot create properties that o does not have.

The above is all the content of this article, hoping to help you learn javascript.

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.