es6 Javascript 类在回调中使用它
es6 Javascript class using this inside a callback
新的 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
}
}
}
有什么解决方案吗?
您有以下选项:
- 使用箭头函数:
class ClassName {
// ...
aMethod(){
const aFun = () => {
this.dir// ACCESS to class reference of this
}
}
}
- 或者
bind()
方法:
class ClassName {
// ...
aMethod(){
var aFun = function() {
this.dir;// ACCESS to class reference of this
}.bind(this);
}
}
- 将
this
存储在专用变量中:
class ClassName {
// ...
aMethod(){
var self = this;
function aFun() {
self.dir;// ACCESS to class reference of this
}
}
}
本文介绍了有关 JavaScript 中this
和箭头函数的必要详细信息。
在 aMethod(( 中引用 dir,然后在 aFunc 中使用它,例如
aMethod() {
var tempDir = this.dir;
aFunc() {
console.log(tempDir);
}
}
相关文章:
- 如何将一个JavaScript函数回调为多个函数
- JavaScript回调函数
- 用于回调的javascript参数
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- Javascript点击事件回调不起作用
- 如何让程序员在javascript中实现正确的回调
- 从多个回调 javaScript 返回最终对象
- 如何使用传递参数回调 JavaScript 对象属性
- 可能从其他域弹出时回调 JavaScript
- 一个函数,它接受回调并创建只能调用一次的新版本的回调.Javascript
- 构造Javascript回调:Javascript/JQuery
- 对象成员函数的回调?(Javascript)
- 回调javascript动画
- 如何将自定义回调javascript参数添加到bing API回调中
- Facebook喜欢按钮回调javascript警告框
- 在Yii2中表单验证后的回调Javascript函数
- ASP.Net ThreadPool委托回调——JavaScript不会在回调线程上触发
- 其他函数中的回调 javascript 函数
- robot -递归回调- JavaScript
- 更好的回调Javascript代码在Express/NodeJs