I understand the JS scope, scope chain and variable promotion

Source: Internet
Author: User

function test4 () {  console.log ("test4:" +a)}test4 (), var a=1;function test () {  var test1=function () {    var Test2=function () {      console.log ("Test>test1>test2:" +a)    }    test2 ();  Test1 ();} function Test3 () {  console.log ("test3:" +a)}test3 (); test ();

The above is a code snippet that runs the following result:

Variable hint: The variable is divided into two stages of declaration and assignment, while the variable promotion is the declaration phase, the assignment is not moved, the variable promotion will declare the variable to the top of the current running environment (the first line of the function start). So the test4 print out is undefined, instead of throwing a errror.

Scope chain: Test2 does not define the TestVal value, but because test2 in test1 so will go to test1 to find value, test1 also undefined, so go to test, finally to global found value, So test prints out a value of 1. From Test2->test1->test->global this line is called the scope chain.

Scope: Test2 and test3 can get the value of TestVal, this is the scope of testval. Scope refers to the valid interval of a variable. Such as:

The box represents the scope. This is called the scope chain of the outermost a from test2 and test4. A declaration position is lifted to the top of the outermost scope, which is called a variable elevation.

There are two ways to declare a function, function start and literal declaration, then the two of those inside is parsing first? On the code:

Console.log (TEST5) var test5=1; function test5 () {}

Result: The statement is parsed first, i.e. the code runs as follows:

var Test5; function Test5 () {}console.log (TEST5) test5=1

Code to write more than test, encountered do not know how to write down run again, or do not understand the words in the question to check.

I understand the JS scope, scope chain and variable promotion

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.