I’m trying to understand why this alerts to true? And how I would be able to alert false without passing arguments to the callback function (if possible)?
var a = true;
function foo(callback){
var a = false;
callback();
}
function bar(){
alert(a);
}
foo(bar); // Alerts true
This:
…is local to the scope of the
foofunction.This:
…was created in the variable scope where
a = true, and as such, closed over that local variable environment, and thus over that specificavariable.It comes down to the fact that whenever you create a function, it permanently retains the variable scope in which it was created.
It doesn’t matter if you pass that function into another environment. It will always only reference its original variable environment.
EDIT:
In order for
barto reference the variables local tofoo, you could pass them in tobaras arguments:Example: http://jsfiddle.net/dSZ4M/
…you’ll notice that I gave the parameter in
bar()the same name as the globalavariable. Because parameters to the function are read before variables outside the function’s own variable environment, theaparameter “shadows” the globalavariable.As such, you can no longer read the global
afrom insidebar. Of course, all you’d need to do is change the name of the parameter to something else, likeargor whatever, and then you’d be able to reference both the localargparameter and the globalavariable.