如何在承诺的 then 回调中设置“this”的上下文

Vit*_*.us 5 javascript this promise

当我打电话resolve()上的无极,其内部的,则函数()被绑定到的范围window

有什么方法可以像使用Function.apply方法一样设置 this 的上下文?

function Point(){
  var that = this;
  
  var _x = 0;
  
  this.setX = function(x){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            _x = x;
            resolve.apply(that); //<== set this
        }, 1000);
    });
  }

  this.getX = function(){
    return _x;
  }
}

var p = new Point();
p.setX(10).then(function(){
  console.log(this.getX()); //this === `window`
});
Run Code Online (Sandbox Code Playgroud)

编辑:

详细说明,使用同步代码,您可以通过简单地一遍又一遍地返回相同的对象来进行方法链。

//this pattern
obj.method1();
obj.method2();
...


//becomes this pattern
obj.method1(10).method2(11) ...
Run Code Online (Sandbox Code Playgroud)

链接的实现

method1 = function(x){
    return this;
}
Run Code Online (Sandbox Code Playgroud)

谈到异步,你仍然可以用回调做同样的事情

obj.method1(10, function(){ this.method2(11, function(){ ...
Run Code Online (Sandbox Code Playgroud)

使用回调实现

method1 = function(x, cb){
    cb.apply(this);
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么有人会将“接收器”函数绑定到窗口,这对我来说没有意义,因为承诺应该类似于同步调用。

Kev*_*Bot 3

选项1:

您可以将实例传递给解析函数。然后通过回调引用它作为第一个参数。

function Point() {
  var that = this;

  var _x = 0;

  this.setX = function(x) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        _x = x;
        resolve(that); //<== set this
      }, 1000);
    });
  }

  this.getX = function() {
    return _x;
  }
}

var p = new Point();
p.setX(10).then(function(scope) {
  console.log(scope.getX());
});
Run Code Online (Sandbox Code Playgroud)

选项2:

您可以绑定回调的范围:

var p = new Point();
p.setX(10).then(function () {
    console.log(this.getX()); //this === `window`
}.bind(p)); // bind the scope here
Run Code Online (Sandbox Code Playgroud)

var p = new Point();
p.setX(10).then(function () {
    console.log(this.getX()); //this === `window`
}.bind(p)); // bind the scope here
Run Code Online (Sandbox Code Playgroud)