Javascript 如何将主干函数作为参数传递

Javascript 如何将主干函数作为参数传递,javascript,jquery,backbone.js,Javascript,Jquery,Backbone.js,我需要将主干视图中的一个函数传递到同一视图中的另一个函数。我使用了下面的方法,这对全局函数很有效。但当涉及主干视图实例时,它不起作用 我认为问题在于传递的函数具有不正确的上下文-请注意,this在控制台中打印不同的对象 如何正确地传递函数并在正确的上下文中调用函数 最简单的方法是将适当的this绑定到函数。大概是这样的: mainFunc: function(){ this.intermediateFunc(this.ABC.bind(this)); } 另一种常见的回调方法是允许调

我需要将主干视图中的一个函数传递到同一视图中的另一个函数。我使用了下面的方法,这对全局函数很有效。但当涉及主干视图实例时,它不起作用

我认为问题在于传递的函数具有不正确的上下文-请注意,
this
在控制台中打印不同的对象

如何正确地传递函数并在正确的上下文中调用函数


最简单的方法是将适当的
this
绑定到函数。大概是这样的:

mainFunc: function(){
    this.intermediateFunc(this.ABC.bind(this));
}
另一种常见的回调方法是允许调用方提供所需的
this
并使用它:

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();
}
这种情况的一种变体可以假设
上下文
intermediateFunc
中应该是

mainFunc: function(){
    this.intermediateFunc(this.ABC, this);
},
intermediateFunc : function(callback, context) {
    console.log(this); //prints the correct view
    context = context || this;
    callback.call(context);
}
mainFunc: function() {
    var _this = this;
    this.intermediateFunc(function() { return _this.ABC() });
}
如果您希望
callback
几乎总是视图的方法之一(或普通函数),那么这可能很有用

另一种方法是使用旧的
var\u this=this
技巧,将匿名函数传递给
intermediateFunc

mainFunc: function(){
    this.intermediateFunc(this.ABC, this);
},
intermediateFunc : function(callback, context) {
    console.log(this); //prints the correct view
    context = context || this;
    callback.call(context);
}
mainFunc: function() {
    var _this = this;
    this.intermediateFunc(function() { return _this.ABC() });
}

由于
intermediateFunc
似乎是来自同一对象的函数(
this.intermediateFunc
),因此可以添加一点,即可以使用
callback.call(this)
@emilebergron True直接调用回调。我可能会将其折叠到
第二个
选项中,并将
作为默认的
上下文