JS Closed Package

Source: Internet
Author: User

The scope of a variable

The special point of the JavaScript language is that the global variables can be read directly inside the function.

On the other hand, a local variable inside a function cannot be read naturally outside the function.

Function F1 () {
var n=999;
}

alert (n); Error

Second, how to read the local variables from the outside?

For a variety of reasons, we sometimes need to get local variables within the function. However, as already mentioned, under normal circumstances, this can not be done, only through the workaround to achieve.

That is, in the inside of the function, define a function. (In the above example, the value of the variable n cannot be accessed outside the function F1, if you want to access the value of the variable n outside the function F1, you need to define a function F2 within the function F1, then F2 is able to access the value of the variable n, and then return the function F2, in this way, Then the value of the variable n can be accessed outside the function F1, where the function F2 is a closure)

 

Function F1 () {

n=999;

function F2 () {
alert (n);
}

return F2;

}

var result=f1 ();

Result (); 999

JS Closed Package

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.