es6 Javascript 类在回调中使用它

es6 Javascript class using this inside a callback

本文关键字:回调 Javascript es6      更新时间:2024-03-04

新的 es6 类允许您在方法内部使用自引用变量this
但是,如果类方法具有子函数或回调,则该函数/回调不再有权访问自引用变量this

class ClassName {
  constructor(dir){
    this.dir = dir;
    fs.access(this.dir, fs.F_OK | fs.W_OK, this.canReadDir);//nodejs fs.access with callback
  }
  canReadDir(err){
    this.dir;// NO ACCESS to class reference of this
  }
  //OR
  aMethod(){
    function aFunc(){
      this.dir;// NO ACCESS to class reference of this
    }
  }
}

有什么解决方案吗?

您有以下选项:

  1. 使用箭头函数:
class ClassName {
  // ...
  aMethod(){
    const aFun = () => {
      this.dir// ACCESS to class reference of this
    }
  }
}
  1. 或者bind()方法:
class ClassName {
  // ...
  aMethod(){
    var aFun = function() {
      this.dir;// ACCESS to class reference of this
    }.bind(this);
  }
}
  1. this存储在专用变量中:
class ClassName {
  // ...
  aMethod(){
    var self = this;
    function aFun() {
      self.dir;// ACCESS to class reference of this
    }
  }
}

本文介绍了有关 JavaScript 中this和箭头函数的必要详细信息。

在 aMethod(( 中引用 dir,然后在 aFunc 中使用它,例如

aMethod() {
    var tempDir = this.dir;
    aFunc() {
        console.log(tempDir);
    }
}