function a(callback) {
var something = 10;
callback(something);
}
a(function(blabla) {
console.log(blabla); // output 10
});
Ok i dont have problem understanding this code.
I know that "something" is local to function a
and but in the sense of closures and fact that execution context is created when function is called i expected following to work also:
function a(callback) {
var something = 10;
callback();
}
a(function() {
console.log(something);
});
So what happened exactly (why second example don't work)?
Obviously everything is garbage collected and not accessible in body of callback function.
In the second example, the local variable something
is not accessible in the body of your callback not because it's garbage collected, but simply because it is out of scope.
Consider this counter-example:
function a(callback) {
callback();
}
var something = 10;
a(function() {
console.log(something);
});
Here something
is in scope at the time the body of the callback is defined so you can reference it. Doing so creates a closure.
Also consider this one:
function foo() {
var xyz = 1;
bar();
}
function bar() {
console.log(xyz);
}
This is functionally the same example as you have: foo
is a
and bar
is the anonymous function passed in as callback
.
Why should calling bar()
result in printing 1
here? That variable is locally scoped inside foo
, and bar
knows nothing about it.
A function can only reference variables that are declared in either:
In other words, the calling scope is not taken into account and so something
is considered undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With