Home  >  Article  >  Web Front-end  >  Use closures and self-executing functions in javascript to solve a large number of global variable problems_javascript skills

Use closures and self-executing functions in javascript to solve a large number of global variable problems_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:12:521577browse

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

Copy code Code As follows:

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:
Copy code The code is 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 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!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn