Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 这在类函数内的函数中未定义_Javascript_Object_Scope - Fatal编程技术网

Javascript 这在类函数内的函数中未定义

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

我有下面的js代码片段(从原始代码略为简化),我无法理解为什么会出现
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);
        }
    });
}

是特定于封闭函数的。我以前确实尝试过此功能,但在回调函数中使用过它……谢谢,效果非常好。