首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >"this“作为对象成员而不是事件处理程序上的节点引用?

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

Stack Overflow用户
提问于 2016-06-10 19:38:56
回答 1查看 32关注 0票数 0
代码语言:javascript
复制
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中发生的那样?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-10 19:42:52

您希望将函数绑定到要使用的this

代码语言:javascript
复制
document.getElementById('xx').addEventListener('click', this.clickHandle.bind(this));

对象函数中的this指函数的调用方,因此当对象调用该函数时,就像在niceObj.init()中一样,this将是niceObj。事件侦听器以this的形式调用事件目标函数。

因此,您可以将事件侦听器函数绑定到对象,如果niceObjinit的调用者,则对象应该是init

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Objects/Function/bind

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37755974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档