首页 > 解决方案 > “未捕获的 TypeError XXX 未定义”在方法中但不在构造函数中

问题描述

我声明了一个这样开始的类:

class Editor {
    constructor() {
        this.note_text = document.getElementById("note_text");
        this.note_preview = document.getElementById('note_preview');
        this.cloze_type = document.getElementById("cloze_type");
        this.cloze_id = document.getElementById("cloze_id");
        this.span_debug = document.getElementById("span_debug");
        this.card_selection = document.getElementById('card_selection');
        this.mode = document.querySelector('input[name="preview_mode"]:checked');
        console.log(this.mode.value);

        this.note_text.oninput = this.display_update;
    }

    display_update() {
        let mode = this.mode.value;
[...]

任何时候display_update()被调用,我都会收到错误消息Uncaught TypeError: this.mode is undefinedlet mode = this.mode.value;但是,console.log(this.mode.value);声明后的行this.mode输出正确的结果。

怎么可能this.mode在构造函数中定义,而不是在方法中定义?

标签: javascript

解决方案


推荐阅读