我遇到了一个奇怪的错误
当我正在使用新版本的 ES6 时。当我运行这段代码时,我得到 ReferenceError: alertBox is not defined
。有什么方法可以在这个函数中调用alertBox吗?预先感谢:)
这是代码
class main {
constructor(data){
this.data=data;
// this one works
this.alertBox(this.data);
this.watchFile(function(){
// this one throws error
this.alertBox(this.data);
});
}
alertBox(data){
alert(data);
}
watchFile(cb){
cb("changed");
}
}
// app.js
new main("hello");
在这里您可以找到代码片段:https://repl.it/FJUo
最佳答案
通过将普通函数传递到 watchFile
中,您将丢失 this
的上下文。在 ES6 中,您可以使用“箭头函数”语法来创建一个保持正确上下文的函数。
this.watchFile(() => {
this.alertBox(this.data);
});
关于javascript - 构造函数中的范围错误 (ES6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650389/