JavaScript variable Promotion

Source: Internet
Author: User

First, the question:

Window.onload=function () {
var bar=1;
function Test () {
Console.log (bar);
}
Test ();
};

Result is 1

Window.onload=function () {
var bar=1;
function Test () {
Console.log (bar);

   var bar=2;
Console.log (bar);

}
Test ();
};

The result is undefined 2

Second, the scope chain:

When you want to access a variable inside the function, first find your own internal scope There is no such variable, if not on the object to find the prototype object , or not, to the scope of the scope of the search, until the Scope where window is located

Third, JavaScript variable promotion

Although the variable bar is defined in the following, but the browser at the time of parsing, the definition of the variable is put in front, the above test function is equivalent to

function Test () {

var bar;

Console.log (bar); Undefined

bar=2;

Console.log (bar); 2

}

the definition of the function will be raised to the front

var foo=function () {

Console.log (1);

};

function foo () {

Console.log (2);

}

Foo (); Result is 1

The above code is equivalent to:

function foo () {

Console.log (2);

}

var foo;

Foo=funciton () {

Console.log (1);

}

Foo (); 1

JavaScript variable Promotion

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.