我很确定这在某个地方得到了解答,但我无法包裹我的头/转移它。我想将一个变量从当前上下文传递给回调的上下文。我不想将它作为参数传递。
doSomething = (callback) ->
testVar = 42
callback()
doSomething -> console.log testVar
这将编译为以下JS代码
var doSomething;
doSomething = function (callback) {
var testVar;
testVar = 42;
return callback();
};
doSomething(function () {
return console.log(testVar);
});
>
testVar is not defined
答案 0 :(得分:1)
1)你可以进行闭包(如果你有变量就可以工作,并在创建时在函数中使用它)
var testVar = 0;
callback = function(){
console.log(testVar);
}
callback();// prints 0
testVar = 45;
callback();// prints 45
2)您可以将变量绑定到函数
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)你可以调用变量来实现功能
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)您可以致电或应用此参考
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