es6 Javascript类使用这个里面的callback

新的es6类允许您在方法内部使用自引用variables。
但是,如果一个类方法有一个子函数或一个callback函数,那么这个函数/callback就不再有权访问自引用variablesthis

 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 } } } 

有没有解决这个问题?

您有以下select:

1)使用箭头function:

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

2)或者bind()方法:

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

3)将其存储在一个专门的variables中:

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

本文将介绍有关JavaScript中的this和箭头函数的必要细节。

在aMethod()中join一个对dir的引用,然后像在

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