如何将其绑定到回调

How to bind this to a callback?

本文关键字:回调 绑定      更新时间:2023-09-26

我之前的问题是重复的,我从重复的帖子中读到了答案,但没有运气。

我添加了一个绑定,正如SO帖子中的答案所建议的那样。但我仍然不确定。

我有一系列的承诺,在每次执行之前,我都会检查用户是否取消了承诺链。

我的问题是,我无法在回调方法中访问"this",下面是一个粗略的例子,我无法访问getMoreData()中的p.test变量

p.test = 'hello!';
p.init = function(){ 
    var self = this;
    this.getData() 
        .then(function(data) {
            return self.shouldContinue(getMoreData,data).bind(self);
        });
}
p.shouldContinue = function(cb, data) {
    // ...
    this.currentRequest = cb.call(this,data);
};
p.getData = function(){
    // return ajax call
};
p.getMoreData = function(){
    console.log(this.test); // undefined
    // return ajax call
};

你试过这个吗
您需要将this绑定到cb

p.test = 'hello!';
p.init = function(){
var self = this;
this.getData() 
    .then(function(data) {
        return self.shouldContinue(getMoreData,data).bind(self);
    })
}
p.shouldContinue = function(cb, data){
   ...
  this.currentRequest = cb(this,data).bind(this);
};
p.getData = function(){
    //return ajax call
};
p.getMoreData = function(){
    console.log(this.test); //undefined
    //return ajax call
};

更改为:

 p.init = function(){ 
      var self = this;
      this.getData() 
          .then(function(data) {
              return self.shouldContinue.bind(self, self.getMoreData, data)();
          });
  }
  1. 将CCD_ 2绑定到CCD_。

  2. .bind返回一个Function,所以需要调用它。所以self.shouldContinue会继续调用self.getMoreData,否则它会留在那里等待调用。

return self.shouldContinue(getMoreData,data).bind(self);

看起来你不小心调用了shouldContinue,并试图绑定它的结果,而不是在不调用它的情况下绑定函数。这应该会得到你需要的。

return self.shouldContinue.bind(self, self.getMoreData, data);

请记住,getMoreData是一个未在变量作用域下定义的函数,因此需要使用. 来访问它

编辑:我也注意到shouldContinue也有类似的问题,但我对您代码的某些部分的意图感到困惑,所以我添加了一条注释来询问更多信息。