"this"作为对象成员身份而不是事件处理程序上的节点引用?


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

因此,您将该事件侦听器函数绑定到对象,如果niceObjinit的调用方,则应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

最新更新