Why does this closure work?

Let's say I have a simple function that warns about a message:

function callMessage(msg){ alert(msg); } 

Now when I call it that, it doesn't work. Throws an 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 works:

 function sayHi(){ var hey = "hi there" setTimeout(function(){callMessage(hey);}, 1000); } sayHi(); 

Why is the variable β€œhey” visible only when I put it in an anonymous function?

+8
javascript closures
source share
3 answers

In the first example, the code is evaluated after the expiration of the timer and the current area. hey is currently undefined.

The second example β€” the correct way to use setTimeout β€” uses the anonymous function created by calling setTimeout() . This anonymous function also gets a copy of the current area.

+14
source share

"callMessage (hey)" is a string, not a closure. It was evaluated when the timeout expires, and at that moment the hey variable is not in scope.

+6
source share

This is normal.

The second example creates what we call the fixture, this is the execution context. hey variable is stored for use by an anonymous function in memory.

In the first example, the hey variable is not stored in the device (since javascript cannot know that you will use the variable after) and therefore cannot be extracted when the string is evaluated

+3
source share