在同一构造函数(JS)中调用方法时“不是函数”

时间:2018-12-18 20:38:21

标签: javascript methods runtime-error class-method

我想在同一个类的方法中调用一个方法。

function Dialog() {

this.close = function() {
    //code
};

this.dialog = document.createElement("div");
this.dialog.onclick = function() {
    this.close();
}
document.body.appendChild(this.dialog);
}

var test = new Dialog();

我搜索了答案,但没有任何帮助:单击div时,浏览器的控制台中仍然显示TypeError: this.close is not a function

2 个答案:

答案 0 :(得分:1)

使用function() { ... }时,它将更改函数内部的this。您需要将函数绑定到this或使用箭头函数() => { ... }

使用绑定:

var handleClick = function() {
    this.close();
};

this.dialog.onclick = handleClick.bind(this)

使用箭头功能:

this.dialog.onclick = () => {
    this.close();
}

答案 1 :(得分:0)

尝试使用close(){}而不是执行this.close = function(){}。参见下面的示例。

function Dialog() {
    close(){
        //code
    };

    this.dialog = document.createElement("div");
    this.dialog.onclick = function() {
        this.close();
    }

    document.body.appendChild(this.dialog);
}

var test = new Dialog();