I={};I.have={};I.have.a={};I.have.a.deep={};I.have.a.deep.deep={};I.have.a.deep.deep.deep={};
I.have.a.deep.deep.deep.niceObj = {
init: function(){
document.getElementById('xx').addEventListener('click', this.clickHandle)
},
some: function(){},
other: function(){
// here I can use *this* as I want
this.some();
},
clickHandle: function(e) {
// can't use *this* as I want becouse *this* reffers to #xx
this.some() // fails!!!
// here I have a trick, but I realy don't want to reffer
// with the full qualified name
I.have.a.deep.deep.deep.niceObj._clickHandle(e);
},
_clickHandle: function(e) {
// here again *this* works as I want
this.some();
}
问题是,如何在嵌入式事件处理程序中省略使用完整的限定对象名称,就像在 clickHandle 中发生的那样?
将函数绑定到要使用的this
。
document.getElementById('xx').addEventListener('click', this.clickHandle.bind(this));
对象函数中的this
是指函数的调用者,因此当您的对象调用该函数时,如在niceObj.init()
中,this
将被niceObj
。事件侦听器调用具有事件目标的函数,this
。
因此,您将该事件侦听器函数绑定到对象,如果niceObj
是init
的调用方,则应this
该对象。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind