Reputation: 610
i have the following code:
function log(a) {
var b = 5;
a();
}
log(function(){
console.log(b);
});
When that anon function is executed at function log, I am getting "b is not defined". Well, It seems like that anon's outer environment reference isn't log's, as If it wasn't created inside of it so therefore it can't find that var. so where is it being created? on the global level? My initial thought was that those parentheses make the anon function created inside of log's.
Upvotes: 0
Views: 150
Reputation: 1337
Every time you call a function, assuming that you do not declare global variables (you didn't declared any), the scope is created for that function and what goes in that scope is determined not by where the function was called but by where it was defined. You can see that where you defined the anonymous function (in the call to log), the variable b
is not in that scope that is why it's not available.
Let's rewrite your code:
function log(a) {
var b = 5;
a();
}
function logger() {
console.log(b);
}
log(logger);
You can see that your code and mine are doing the same thing, the only difference is that mine code doesn't have an anon function. They do not share common variables in their scopes.
Now check this out:
var b = 5;
function log(a) {
a();
}
function logger() {
console.log(b);
}
log(logger);
Now both log and logger share a common variable b in their scopes (log is not using b so if you check it in a debugger it will be undefined). As I say you don't determine scope by where function was called but by where and how it was declared.
Upvotes: 1
Reputation: 9284
In JavaScript scopes exists within functions. So your b variable is visible only within its scope - the anonymous function. If you want it to be visible outside the function then you can assign the variable to the global scope.
function log(a) {
window.b = 5;
a();
}
log(function(){
console.log(b);
});
Upvotes: 0