Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

callback function, closure and execution context

Tags:

javascript

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.

like image 345
Srle Avatar asked Feb 12 '23 18:02

Srle


2 Answers

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.

like image 112
Jon Avatar answered Feb 15 '23 07:02

Jon


A function can only reference variables that are declared in either:

  1. the function body,
  2. the function arguments (applies in 1st example),
  3. the scope where the function was declared.

In other words, the calling scope is not taken into account and so something is considered undefined.

like image 40
Ja͢ck Avatar answered Feb 15 '23 09:02

Ja͢ck