But from a global perspective, this will lead to some situations that are difficult for us to control: variables with the same name, value transformation after multiple functions share a global variable... and so on. So, sometimes, for some simple global variables, we can deal with it in another way - using self-executing function closure method to solve it:
For example: we want to give it when the web page is loaded A prompt, giving another prompt when the web page is closed
The following code implements the above function
var msg1 = "Welcome!"; // Define a global variable
var msg2 = "Goodbye!" // Define another global variable
window.onload = function() {
alert(msg1);
}
window.onunload = function() {
alert(msg2);
}
this Two global variables have been used in the code snippet. It's just to implement a simple function.
Moreover, there are too many global variables, we must remember: msg1 is the variable when welcome, msg2 is the variable when closing... If there are more variables, can we still remember them?
The following is the same function, but using the self-executing function closure method:
(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 has grown, but:
1) msg variables are only executed in their respective Valid within the function. There will be no confusion with other global variables.
2) The structure of the code becomes clearer.
3) Solve the situation where a large number of global variables are used.
The above is just my personal understanding. I hope real experts can give their comments!