访问eventListener函数Javascript中的类方法
我有一个类名对话框。在这个类中,我有一个方法hide()来隐藏对话框本身及其模式框。但我无法从“onclick”函数访问隐藏函数。我如何访问它访问eventListener函数Javascript中的类方法,javascript,class,object,this,this-keyword,Javascript,Class,Object,This,This Keyword,我有一个类名对话框。在这个类中,我有一个方法hide()来隐藏对话框本身及其模式框。但我无法从“onclick”函数访问隐藏函数。我如何访问它 class Dialog{ constructor(id){ this._dialogBox = $('.dialog#'+this.id); this._closeButton = this._dialogBox.find('span.closedialog'); this._closeButt
class Dialog{
constructor(id){
this._dialogBox = $('.dialog#'+this.id);
this._closeButton = this._dialogBox.find('span.closedialog');
this._closeButton.on('click', function(){
//how to access hide() function from here?
});
}
hide(){
this._dialogBack.hide();
this.dialogBox.hide();
}
}
Javascripts
此
上下文在事件侦听器中更改。您可以通过将此上下文添加到单独的变量来解决此问题:
class Dialog{
constructor(id){
this._dialogBox = $('.dialog#'+this.id);
this._closeButton = this._dialogBox.find('span.closedialog');
const self = this;
this._closeButton.on('click', function(){
//how to access hide() function from here?
self.hide()
});
}
hide(){
this._dialogBack.hide();
this.dialogBox.hide();
}
}
如您所见,我将
this
上下文分配给变量self
。之后,您可以使用self访问类上下文。我认为这应该适合您
this.\u closeButton.on('click',this.hide.bind(this));
事件侦听器中的上下文不同,因此您应该将实际的
this
绑定到事件侦听器上下文如果您使用es6+。。箭头函数不会覆盖此
class Dialog{
constructor(id){
this._dialogBox = $('.dialog#'+this.id);
this._closeButton = this._dialogBox.find('span.closedialog');
this._closeButton.on('click', () => {
this.hide();
});
}
hide(){
this._dialogBack.hide();
this.dialogBox.hide();
}
}````
与这个问题无关,我不禁注意到将
span.closedialog
更改为button.closedialog
(HTML)可能是个好主意。这改进了HTML语义,并为可用性和可访问性带来了显著的好处。尝试仅使用键盘选项卡键来集中范围。。。如果使用适当的语义,所有这些都是免费的