我创建了以下类:
class GlobalModal {
constructor(text) {
this.modal = document.getElementById('Modal');
this.span = document.getElementById("closeModal");
this.text = text;
//Show the GlobalModal
this.modal.style.display = "block";
// When the user clicks on <span> (x), close the modal
this.span.onclick = function() {
this.close();
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == this.modal) {
this.close();
}
}
}
// Function to close the GlobalModal
close() {
this.modal.style.display = "none";
}
}
我正在尝试调用函数this.close();
错误:关闭不是一个函数。
我想做的事情有可能吗?我做错了什么?
如果你想在回调中使用this
,你应该使用一个将this
绑定到词法上下文的箭头函数:
window.onclick = (event) => {
if (event.target == this.modal) {
this.close();
}
}
class GlobalModal {
constructor(text) {
this.modal = document.getElementById('Modal');
this.span = document.getElementById("closeModal");
this.text = text;
//Show the GlobalModal
this.modal.style.display = "block";
// When the user clicks on <span> (x), close the modal
this.span.onclick = function() {
this.close();
}.bind(this)
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == this.modal) {
this.close();
}
}.bind(this)
}
// Function to close the GlobalModal
close() {
this.modal.style.display = "none";
}
}
正如@ibrahim mahrir所指出的,您在事件侦听器中丢失了this
的上下文。bind
显式地将this
值设置为您作为参数给定的值。