es6 Javascript类在回调中使用它

fre*_*tma 16 javascript node.js ecmascript-6

新的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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这有什么解决方案吗?

Dmi*_*tin 27

您有以下选择:

1)使用箭头功能:

class ClassName {
  // ...
  aMethod(){
    let aFun = () => {
      this.dir;// ACCESS to class reference of this
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

2)或bind()方法:

class ClassName {
  // ...
  aMethod(){
    var aFun = function() {
      this.dir;// ACCESS to class reference of this
    }.bind(this);
  }
}
Run Code Online (Sandbox Code Playgroud)

3)存储this在一个专门的变量中:

class ClassName {
  // ...
  aMethod(){
    var self = this;
    function aFun() {
      self.dir;// ACCESS to class reference of this
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

本文介绍了thisJavaScript中有关箭头函数的必要细节.

  • 您将如何编写 canReadDir(err) 函数(只是为了使示例完整)? (2认同)