Given the following code, what should I expect to see in the alert?
var a = 100;
function afunc(infunc){
a = 10;
infunc.call();
}
afunc(function(){alert(a)});
My initial thought was that my browser should alert 100 since the variable a=100 would be in scope for the anonymous function passed as an argument to afunc. But this assumes that the anonymous function is actually defined in the global context. Apparently that’s not the case as the browser alerts 10. So why is a=10 ahead of a=100 in the scope chain?
Thanks!
Because you’re setting a to 10 before you call the anonymous function. a is in fact global, but you’re setting it to 10.