Jan Wirth
Jan Wirth

Reputation: 460

Javascript / Coffeescript: Can I pass a variable from current context to a callback function?

I am pretty sure this is answered somewhere, but I just can't wrap my head/transfer it. I want to pass a variable from the current context to the context of a callback. I do not want to pass it as parameter.

doSomething = (callback) ->
    testVar = 42
    callback()
doSomething -> console.log testVar

this compiles to the following JS code

var doSomething;
doSomething = function (callback) {
    var testVar;
    testVar = 42;
    return callback();
};
doSomething(function () {
    return console.log(testVar);
});

> testVar is not defined

Upvotes: 0

Views: 312

Answers (1)

Alex Nikulin
Alex Nikulin

Reputation: 8679

1)You can make closure (works if you have variable and use it in a function at moment of creation)

var testVar = 0;
callback = function(){
  console.log(testVar);
}
callback();// prints 0
testVar = 45;
callback();// prints 45

2)You can bind variable to function

callback = function(testVar){
    console.log(testVar);
}
// first arg will be "this" reference in function, second arg and more will be arguments
callback.bind(this, 45);// will be always until new bind 
callback(); //prints 45
callback(); //prints 45

3)You can call variable to function

callback = function(testVar){
    console.log(testVar);
}
// first arg will be "this" reference in function, second arg and more will be arguments
callback.call(this, 45);//prints 45 only when you exec call
callback() // prints undefined

4) You can call or apply this reference

 callback = function(){
    console.log(this);
 }
 // first arg will be "this"
 callback.call(45);//prints 45 only when you exec call
 callback() // prints function ... default this
 callback.bind(45);
 callback(); // prints 45
 callback(); // prints 45

Upvotes: 1

Related Questions