【发布时间】:2016-07-29 14:59:16
【问题描述】:
新的 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
}
}
}
有什么解决办法吗?
【问题讨论】:
-
你可以创建一个箭头函数来代替
const aFunc = () => this.dir; -
"新的 es6 类允许您在方法中使用自引用变量 this。" - 呃,不,这与 ES6
class语法无关。this关键字的工作方式与在方法中一样。 -
这不是真正的重复,因为这与 es6 类有关,而不仅仅是回调
-
你是否使用一个类并不重要。函数就是函数,不管它是如何创建的。您接受的答案中的解决方案与他在副本中建议的解决方案完全相同。
标签: javascript node.js ecmascript-6