function - Javascript Callback Scoping Issue -


i reading douglas crockford's book on javascript , having issues function scoping section. under impression callback function's value bound value of function calling callback (in case dosomethingasync). however, when run code, foo printed, far dosomethingasync concerned, foo undefined. shouldn't mean callback doesn't have access var well?

function dosomething() {   var foo = "foo";   dosomethingasync(function callback() {     console.log(foo); //prints foo   }); } 

this , variables different 1 another.

this set how function called, not it's defined, although bound functions , es6's arrow functions change (more below). callback isn't bound , isn't arrow function, value of this within callback you're giving dosomethingasync determined how dosomethingasync calls function. if calls standalone function:

callback(); 

...then this undefined (in strict mode) or reference global object (in loose mode).

but if calls specifying this value:

// making object property , using call it: var obj = {callback: callback}; obj.callback(); // `this` `obj`  // using function#call or function#apply callback.call(foo); // `this` `foo` 

...then this different.

more (on blog):

the variables in scope function, though, determined function defined. callback called closure, means has enduring reference context in created (and context around that, , on , including global context), including variables , other things in context. when callback references foo, javascript engine first looks within callback and, not finding there called foo, looks @ containing context. finding foo there, uses it.

that context reference closure has not include this, (except arrow functions), because this more function argument variable (except arrow functions).

more (on blog):


"bound" functions functions function#bind. 1 of features of them this value set argument give function#bind, ignoring 1 supplied when they're called (if any).

es6 "arrow" functions do inherit this context created, making them different other kinds of functions.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -