我需要将 Backbone View 中的函数传递到同一 View 中的另一个函数。我使用了以下方法,该方法适用于全局函数。但当涉及到 Backbone View 实例时,它就不起作用了。
我认为问题在于传递的函数具有不正确的上下文 - 请注意 this
在控制台中打印不同的对象。
如何正确传递函数并在正确的上下文中调用函数?
//Backbone view
mainFunc: function(){
this.intermediateFunc(this.ABC);
}
intermediateFunc : function(callback){
console.log(this); //prints the correct view
callback();
}
ABC : function(){
console.log(this); //prints 'window' when passed through a function
}
最佳答案
最简单的方法是使用 Function.prototype.bind
将适当的 this
绑定(bind)到您的函数。像这样的事情:
mainFunc: function(){
this.intermediateFunc(this.ABC.bind(this));
}
回调的另一种常见方法是允许调用者提供所需的 this
和 Function.prototype.call
或Function.prototype.apply
使用它:
mainFunc: function(){
this.intermediateFunc(this.ABC, this);
},
intermediateFunc : function(callback, context) {
console.log(this); //prints the correct view
if(context)
callback.call(context);
else
callback();
}
这种情况的一个变体可以假设 context
应该是 intermediateFunc
中的 this
:
mainFunc: function(){
this.intermediateFunc(this.ABC, this);
},
intermediateFunc : function(callback, context) {
console.log(this); //prints the correct view
context = context || this;
callback.call(context);
}
如果您期望回调
几乎始终是 View 的方法之一(或普通函数),这可能会很有用。
另一种方法是使用旧的 var _this = this
技巧并将匿名函数传递给 intermediateFunc
:
mainFunc: function() {
var _this = this;
this.intermediateFunc(function() { return _this.ABC() });
}
关于javascript - 如何将 Backbone 函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40734501/