首页 > 解决方案 > 在 Promise 或 Callbacks (JavaScript ES6) 中处理此问题的正确方法

问题描述

是否有正确或“更好”的处理方式this是带有 Promises(甚至是回调)的 JavaScript 类

目前我只是通过这样做来解决这个问题

 var self = this;

但这对我来说感觉很“骇人听闻”。

忽略下面的大部分代码,这只是为了表达我的意思。

 class thing {
  drawthing(thing) {
  console.log(thing);	
  }

  updatethings(thing) {
      var self = this;  //a better way to do this
      return new Promise(function (resolve) {
           setTimeout(function(){
               self.drawthing(thing);
               return resolve(thing);
           },2000);
      });
  }
}

var t = new thing();
t.updatethings('hello').then(console.log);

标签: javascriptclassecmascript-6

解决方案


箭头函数将为您完成此操作。在此处查看一些解释和示例

这是一个更正的片段:

class thing {
  drawthing(thing) {
      console.log(thing);   
  }

  updatethings(thing) {
          // arrow func
          return new Promise((resolve) => {
               // another arrow func
               setTimeout(() => {
                   // Because of arrow function scoping, `this` passes through.
                   this.drawthing(thing);
                   return resolve(thing);
               },2000);
          });
      }
}

var t = new thing();
t.updatethings('hello').then(console.log);

推荐阅读