首页 > 解决方案 > 在同一个构造函数(JS)中调用方法时“不是函数”

问题描述

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

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();

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

标签: javascriptmethodsruntime-errorclass-method

解决方案


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

使用绑定:

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

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

使用箭头函数:

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

推荐阅读