es6 Javascript类在回调中使用
新的es6类允许您在方法内部使用自参考变量es6 Javascript类在回调中使用,javascript,node.js,ecmascript-6,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
。但是,如果类方法具有子函数或回调,则该函数/回调不再具有对自引用变量
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
}
}
}
有什么解决办法吗?在aMethod()中引用dir,然后在aFunc中使用它
aMethod() {
var tempDir = this.dir;
aFunc() {
console.log(tempDir);
}
}
您有以下选项: 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) 将此存储在专用变量中:
class ClassName {
// ...
aMethod(){
var self = this;
function aFun() {
self.dir;// ACCESS to class reference of this
}
}
}
描述有关JavaScript中的
this
和arrow函数的必要详细信息。您可以创建arrow函数代替const aFunc=()=>this.dir代码>使用。“新的es6类允许您在这个方法内部使用自引用变量。”-呃,不,这与es6class
语法无关。this
关键字的工作方式与方法中的工作方式相同。它实际上不是重复的,因为它与es6类相关,而不仅仅是回调。是否使用类并不重要。无论函数是如何创建的,它都是一个函数。您接受的答案中的答案与副本中的答案完全相同。self不是一个保留词吗?@Bálint Nope<可以使用code>self
。第二个选项很好,使用arrow也很有效。您如何编写canReadDir(err)函数(只是为了使示例完整)?bind()
方法工作得很好,并且易于阅读(y)使用var self=this代码>或var=this代码>以后再使用它已经是一个非常好的实践。