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中发生的那样?
发布于 2016-06-10 19:42:52
您希望将函数绑定到要使用的this。
document.getElementById('xx').addEventListener('click', this.clickHandle.bind(this));对象函数中的this指函数的调用方,因此当对象调用该函数时,就像在niceObj.init()中一样,this将是niceObj。事件侦听器以this的形式调用事件目标函数。
因此,您可以将事件侦听器函数绑定到对象,如果niceObj是init的调用者,则对象应该是init。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://stackoverflow.com/questions/37755974
复制相似问题