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

标签 javascript 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 中发生的那样?

最佳答案

您想要将该函数绑定(bind)到 this您想要使用的。

document.getElementById('xx').addEventListener('click', this.clickHandle.bind(this));

this对象中的函数指的是函数的调用者,因此当你的对象调用该函数时,如niceObj.init() , this将是niceObj 。事件监听器调用事件目标为 this 的函数。 .

因此,您将该事件监听器函数绑定(bind)到该对象,该对象应该是 this如果niceObj来电者是init .

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

关于javascript - "this"作为对象成员资格而不是事件处理程序上的节点引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755974/

相关文章:

javascript - 将整个下拉菜单从一个站点复制到另一个站点

javascript - 我可以使用 jQuery 让浏览器在一定时间后跟随链接吗?

Javascript/jQuery/JSON/localStorage 游戏,无法按数字排序排名表

javascript - 如何从数组的 ForEach 循环中引用我的 TypeScript 类中的这个父方法?

c++ - 如何自动更新重写方法的 *this 返回类型?

javascript - mocha测试中以下js箭头函数中 `this`指向什么?

java - 内部类实例变量遮蔽

javascript - 将 JSON 对象数组动态放入表中的有效方法是什么?

javascript - 有没有办法发现page中的某个table是一个dataTable对象呢?

java - 是否可以在构造函数中使用此类实例?