Javascript 这在类函数内的函数中未定义
我有下面的js代码片段(从原始代码略为简化),我无法理解为什么会出现Javascript 这在类函数内的函数中未定义,javascript,object,scope,Javascript,Object,Scope,我有下面的js代码片段(从原始代码略为简化),我无法理解为什么会出现TypeError:this.onError(event.error.message)行的未定义。我知道此在范围内无效,但我不知道为什么 如何解决此问题而不必将onError传递给initialize()方法 class Class1{ constructor(props) { this.class2 = Class2(props.publicKey); this.onError = p
TypeError:this.onError(event.error.message)
行的未定义。我知道此
在范围内无效,但我不知道为什么
如何解决此问题而不必将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);
}
});
}
}
将此
上下文分配给变量,并在回调函数中使用它:
initialize() {
var that = this;
//add error handler
this.class2.addEventListener("change", function (event) {
if (event.error) {
that.onError(event.error.message);
}
});
}
此
是特定于封闭函数的。我以前确实尝试过此功能,但在回调函数中使用过它……谢谢,效果非常好。