Javascript 从类内的构造函数调用函数
我创建了以下类:Javascript 从类内的构造函数调用函数,javascript,javascript-objects,Javascript,Javascript Objects,我创建了以下类: class GlobalModal { constructor(text) { this.modal = document.getElementById('Modal'); this.span = document.getElementById("closeModal"); this.text = text; //Show the GlobalModal this.modal.style.
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.modal=document.getElementById('modal');
this.span=document.getElementById(“closeModal”);
this.text=文本;
//显示全球模式
this.modal.style.display=“block”;
//当用户单击(x)时,关闭模式对话框
this.span.onclick=函数(){
这个。关闭();
}
//当用户单击模式之外的任何位置时,将其关闭
window.onclick=函数(事件){
if(event.target==this.modal){
这个。关闭();
}
}
}
//函数关闭全局模式
关闭(){
this.modal.style.display=“无”;
}
}
我正在尝试调用函数this.close()代码>
错误:此关闭不是功能
我想做的事可能吗?我做错了什么?如果要在回调中使用this
,则应使用将this
绑定到词法上下文的箭头函数:
window.onclick = (event) => {
if (event.target == this.modal) {
this.close();
}
}
类全局模式{
构造函数(文本){
this.modal=document.getElementById('modal');
this.span=document.getElementById(“closeModal”);
this.text=文本;
//显示全球模式
this.modal.style.display=“block”;
//当用户单击(x)时,关闭模式对话框
this.span.onclick=函数(){
这个。关闭();
}.绑定(此)
//当用户单击模式之外的任何位置时,将其关闭
window.onclick=函数(事件){
if(event.target==this.modal){
这个。关闭();
}
}.绑定(此)
}
//函数关闭全局模式
关闭(){
this.modal.style.display=“无”;
}
}
正如@ibrahim mahrir所指出的,您在事件侦听器中丢失了这个的上下文bind
将this
值显式设置为作为参数给定的任何值。在事件侦听器中,this
指触发事件的元素,而不是类实例。我肯定这件事有人骗了你,所以
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";
}
}