【发布时间】:2018-04-25 09:35:55
【问题描述】:
我有以下 js 代码 sn-p(与原始代码相比略有简化),但我无法弄清楚为什么我在 this.onError(event.error.message) 行中得到了 TypeError: this is undefined。我知道this 在范围内无效,但我不知道为什么。
如何在不将onError 传递给initialize() 方法的情况下解决这个问题?
class Class1{
constructor(props) {
this.class2 = Class2(props.publicKey);
this.onError = props.onError;
}
//initialize the form
initialize() {
//add error handler
this.class2.addEventListener("change", function (event) {
if (event.error) {
this.onError(event.error.message);
}
});
}
}
【问题讨论】:
-
this特定于封闭函数。
标签: javascript object scope