JS scope and scope chain details _ basic knowledge

Source: Internet
Author: User
This article mainly introduces JS scope and scope chain details, which are very detailed and comprehensive. we recommend them to our friends here. if you need them, you can refer to them. (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.

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

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

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

The 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

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

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

The 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?

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

The 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:

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

The code is as follows:





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.