【问题标题】:This is undefined in function inside class function [duplicate]这是在类函数内部的函数中未定义的[重复]
【发布时间】: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


【解决方案1】:

将this上下文分配给变量并在回调函数中使用:

initialize() {
    var that = this;
    //add error handler
    this.class2.addEventListener("change", function (event) {
        if (event.error) {
            that.onError(event.error.message);
        }
    });
}

【讨论】:

  • 我之前确实尝试过,但在回调函数中使用了它...谢谢,工作得很好。
猜你喜欢
  • 1970-01-01
  • 2016-12-23
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
相关资源
最近更新 更多