


Use closures and self-executing functions in javascript to solve a large number of global variable problems_javascript skills
May 16, 2016 pm 06:12 PMBut 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What is the meaning of closure in C++ lambda expression?

How to implement closure in C++ Lambda expression?

What are the advantages and disadvantages of closures in C++ functions?

Solve the memory leak problem caused by closures

The impact of function pointers and closures on Golang performance

How to effectively avoid memory leaks in closures?

How are closures implemented in Java?

Chained calls and closures of PHP functions
