Callback function, close and execute context

function a(callback) {
    var something = 10;

    callback(something);
}

a(function(blabla) {
    console.log(blabla); // output 10
});

I have no problem understanding this code.

I know that “something” is local to function a, but in the sense of closures and the fact that the execution context is created when the function is called , which I expect further to work:

function a(callback) { 
    var something = 10; 

    callback(); 
} 

a(function() { 
    console.log(something); 
}); 

So what happened (why does the second example not work)?
Obviously, all the garbage is collected and inaccessible in the body of the callback function.

+4
source share
5 answers

A function can only refer to variables declared in:

  • function body
  • function arguments (used in the first example),
  • The area in which the function was declared.

, something undefined.

+1

something , , , .

:

function a(callback) { 
    callback(); 
} 

var something = 10; 

a(function() { 
    console.log(something); 
});

something , , . .

:

function foo() {
    var xyz = 1;
    bar();
}

function bar() {
    console.log(xyz);
}

, : foo is a bar - , callback.

bar() 1 ? foo, bar .

+4

, something a, , a.

something a, . , something , , . , a, .

, , , :

function a(callback) { 
    var something = 10; 

    callback(); 
} 

function b() { 
    console.log(something); 
}

a(b); 

, , .

+1

: -

function a(callback) {
    var something = 10;

    callback(something);
}

a(function(blabla) {
    console.log(blabla); // output 10
});

blabla - , , a. , - blabla.

: -

function a(callback) { 
    var something = 10; 

    callback(); 
} 

a(function() { 
    console.log(something); 
}); 

- , / .

, js, undefined.

, - a

+1

: , , something, .

Vs. something a. something , a .

:

var something = "Global something";

function a(callback) {
   var something = "Local something";
   callback(something);
}

a( console.log ); // "Local something"

, console.log() something, a , . .

a( function() {console.log(something)} ); //"Global something"

inline, something.

something, a, , . , JS .

console.log something, . "Global something" . .

a( function(x) {console.log(x)} ); //"Local something"

x.

x something, a, , , "Local something", . .

0

Source: https://habr.com/ru/post/1543854/


All Articles