JavaScript's function scope and declaration in advance

Source: Internet
Author: User

Don't say a word; first a piece of code;

var scope= ' global '; function test () {alert (scope);      Output undefine, not global var scope= ' local ';        alert (scope); Output local}test ();

You may think that the first alert will output global;

But in fact the first alert output is undefined;

What's going on here?

To explore this problem first of all to explain the next two concepts;

1: Function Scope:

function scope refers to the variables declared within the function are only valid within this function;

2: Declaration in advance:

Declaration in advance means that a variable declared anywhere within a function will be first parsed at the top of the function;


After understanding the concept of declaration in advance, the above code is equivalent to the following;

If this statement is not literally understood in advance, then it is easy to understand from the code;

var scope= ' global '; function test () {var scope;        The variable alert (scope) is declared first.       Because it is not yet assigned, so it is undefine scope= ' local ';        Assignment alert (scope); Output local}test ();

So the experience is that in the function body first the variables to be used are declared at the beginning of the function;

Instead of declaring variables when they are used;

As to why the first alert is not an output global;

Because the local variables in the function body will obscure the global variables;

Must not explain too much;

650) this.width=650, "alt=" Bai Jun Remote Blog "src=" http://www.baijunyao.com/Upload/image/ueditor/20151126/1448548721566957. PNG "title=" Bai Jun Haruka Blog "/>




Function scope and declaration of JavaScript in advance

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.