Say I have a simple function that alerts a message:
function callMessage(msg){
alert(msg);
}
Now when I call it like so, it does not work. Throws error "hey is not defined"
function sayHi(){
var hey = "hi there"
setTimeout("callMessage(hey)", 1000);
}
sayHi();
But when I call it inside an anonymous function it does work:
function sayHi(){
var hey = "hi there"
setTimeout(function(){callMessage(hey);}, 1000);
}
sayHi();
Why is the "hey" variable only visible when I put it inside an anonymous function?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.
A closure is simply a more convenient way to give a function access to local state. Rather than having to create a class which knows about the local variable you want the function to use, you can simply define the function on the spot, and it can implicitly access every variable that is currently visible.
Advantages of closures They allow you to attach variables to an execution context. Variables in closures can help you maintain a state that you can use later. They provide data encapsulation. They help remove redundant code.
In the first example, the code is evaluated after the timer expired and the current scope was left. hey
is undefined at that moment.
The second example - the proper way to use setTimeout
- uses an anonymous function created when invoking setTimeout()
. This anonymous function also receives a copy of the current scope.
"callMessage(hey)" is a string, not a closure. It's evaluated when the timeout runs, and at this point the variable hey isn't in scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With