自引用类

Rya*_*son 1 javascript class this

我正在学习 JS 课程,遇到了一个问题。当我失去这个上下文时,比如在 Promise 之后,我无法弄清楚如何自引用我的类变量(在构造函数中设置)。

例如:

class myClass{
    constructor(name) {
        this.name = name;
        doSomething().then(doSomethingElse)
    }

    doSomething(){
        return new Promise((resolve, reject)=>{
            resolve("myAsyncName")
        })
    }

    doSomethingElse(value){
        this.name = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

在 doSomethingElse 函数中,我会收到一个错误,指出 this 未定义或无法为其设置名称。我尝试在构造函数中设置 self = this ,它可以工作,但如果我多次使用该类,则会中断。我只需要能够引用构造函数中设置的变量。我尝试搜索许多帖子并阅读大量有关如何使用它和绑定的文章,但我找不到在这种情况下需要使用的模式。

Was*_*eem 5

这是由于doSomethingElse调用的上下文所致。在您的示例中,this使用的 indoSomethingElse将引用 的上下文then,而不是您的类。

有几种方法可以解决这个问题:

1. 始终将方法绑定到类本身。

constructor(name) {
  this.name = name;

  // binding the `this` context
  this.doSomethingElse = this.doSomethingElse.bind(this);
  // the this in doSomethingElse will always refer the class now
  doSomething().then(doSomethingElse)
}

doSomethingElse() {
Run Code Online (Sandbox Code Playgroud)

2. 使用 ES6 粗箭头在词法上绑定上下文

constructor(name) {
  this.name = name;
  doSomething().then(() => this.doSomethingElse())
}
Run Code Online (Sandbox Code Playgroud)

3. 使用transform-class-propertiesfor babel(适用于高级用户)

现在这个还不是官方 ecmascript 规范的一部分,所以我不鼓励使用它。我假设您正在或在某个时候将使用babel. 如果没有,那完全没问题!

有了这个插件,你应该能够编写如下内容:

class myClass{
  constructor(name) {
    this.name = name;
    // no need to change anything here
    doSomething().then(doSomethingElse)
  }

  doSomething(){
    return new Promise((resolve, reject)=>{
        resolve("myAsyncName")
    })
  }

  // notice the fat arrow syntax here. `this` will always be
  // referencing myClass
  doSomethingElse = (value) => {
    this.name = value;
  }
}
Run Code Online (Sandbox Code Playgroud)

我强烈建议阅读 Kyle Simpson 的《你不知道 JS:this 和对象原型》来了解这个主题。

祝您 Javascript 学习之旅顺利!