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!