我想在同一个类的方法中调用一个方法。
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
。
答案 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();