Using closures and self-executing functions in JavaScript to solve a large number of global variable problems _javascript techniques

Source: Internet
Author: User
Tags closure
But from the overall perspective, this can lead to some situations that are difficult for us to control: the variable with the same name, the transformation of the values of multiple functions that share a global variable ... Wait a minute. So, sometimes, for some simple global variables, we can do it in a different way--using the self-executing function + closure method:

For example: We want to give a hint when the page is loaded, give another hint when the page closes
The following code implements the above functionality
Copy Code code as follows:

var MSG1 = "Welcome!"; Define a global variable
var MSG2 = "Goodbye!" "//Set another global variable
Window.onload = function () {
alert (MSG1);
}
Window.onunload = function () {
alert (MSG2);
}

Two global variables have been used in this code. And just to achieve a simple small function.
Moreover, there are too many global variables, we must remember: MSG1 is a welcome variable, MSG2 is a closed-time variable ... If we have more variables, can we remember them?


The following are the same features, but using the self-execution function + closure method:
Copy Code code as follows:

(function () {
var msg = "Hello, world!";
Window.onload = function () {
Alert (msg);
}
})();

(function () {
var msg = "Hello, world!";
Window.onunload = function () {
Alert (msg);
}
})();

The latter approach, although the code grew, however:
1 the MSG variable is valid only within its own execution function. Does not create confusion with other global variables.
2 The structure of the code becomes clearer.
3 solves the problem of using global variables in large quantities.

The above is just my little understanding, I hope the real master to give a comment!
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.