新的 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(){
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) 将 this
存储在专用变量中:
class ClassName {
// ...
aMethod(){
var self = this;
function aFun() {
self.dir;// ACCESS to class reference of this
}
}
}
This article描述了 JavaScript 中关于 this
和箭头函数的必要细节。
关于javascript - es6 Javascript 类在回调中使用 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36498029/