javascript - 如何在 promise 的 then 回调中设置 `this` 的上下文

标签 javascript promise this

当我在 Promise 上调用 resolve() 时, then() 中的函数绑定(bind)到 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`
});

编辑:

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

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


//becomes this pattern
obj.method1(10).method2(11) ...

链接的实现

method1 = function(x){
    return this;
}

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

obj.method1(10, function(){ this.method2(11, function(){ ...

回调实现

method1 = function(x, cb){
    cb.apply(this);
}

我不明白为什么有人会将“receiver”函数绑定(bind)到窗口,这对我来说没有意义,因为 promises 应该类似于同步调用。

最佳答案

选项 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());
});

选项 2:

您可以绑定(bind)回调的范围:

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

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 === instance of Point
}.bind(p));

关于javascript - 如何在 promise 的 then 回调中设置 `this` 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41966403/

相关文章:

javascript - 为什么 fetch 在捕获错误后仍返回?

javascript - Nodejs - promise ,未处理的终止和内存泄漏

javascript - js ES6多态性中如何使用this和super

javascript - 在另一个对象的 foreach 函数中访问对象的 "this"?

c# - 这个和base的区别

javascript - 'require' 与 'import' es6 有何不同?

javascript - 如何获取json对象标题

javascript - 哪个是查找 Item - 对象或对象数组中的多个属性的好方法?

javascript - 如何使用javascript检测android设备中的键盘关闭事件

node.js - Nodejs 中的 jQuery.when() 相当于什么?