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?
javascript closures
levi
source share