This article translates the JavaScript Tutorial playlist of up master Kudvenkat on YouTube
SOURCE Address here:
https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b
In this video we will discuss a simple JavaScript closure example. Every time we click on the button on the page, we want to increase the click Count by 1. To achieve this goal, we have many channels.
First we can use a global variable, and then each time we click the button, the variable increases by 1: The problem with this method is that because Clickcount is a global variable, any script on the page may inadvertently change the value of the variable.
<script type= "Text/javascript" > var clickcount = 0; </script><input type= "button" value= "click Me" onclick= "alert (++clickcount);"/>
The second method is to implement a local variable in a function, and each time we click on the button, we exhale the function and increase the value of its local variable. The problem with this approach is that no matter how many times you click the button, the Clickcount value will not exceed 1.
<script type= "Text/javascript" > function incrementclickcount () { var clickcount = 0; return + +clickcount; } </script><input type= "button" value= "click Me" onclick= "alert (Incrementclickcount ());"/>
So the third method is to use JavaScript closures, a closure is an intrinsic function in an external function, and this inner function can use the variables of the external function, its own internal variables, and even global variables. In a nutshell, closures are functions in functions, These external and intrinsic functions can be known functions or anonymous functions. In the following example, we use an anonymous function in the anonymous function to implement. The variable incrementclickcount is given the value of the returned self-activating anonymous function.
<script type= "Text/javascript" > var incrementclickcount = (function () { va R clickcount = 0; return function () { return ++click Count; } })(); </script><input type= "button" value= "click Me" onclick= "alert (incrementclickcount);"/>
<script type= "Text/javascript" > var incrementclickcount = (function () { var clickcount = 0; return function () { return + +clickcount; } }) (); </script><input type= "button" value= "click Me" onclick= "alert (Incrementclickcount ());"/>
Translation Various examples of closures in JavaScript