Event Handler Called With Wrong Context

安稳与你 提交于 2019-12-12 05:28:40

问题


In the SomeObj object, the onkeydown event handler this.doSomething is called in the wrong context (that of the textbox element) but it needs to be called in the context of this. How can this be done?

function SomeObj(elem1, elem2) {
    this.textboxElem = elem1;
    this.someElem = elem2;
    this.registerEvent();
}

SomeObj.prototype = {
    registerEvent: function() {
        this.textboxElem.onkeydown = this.doSomething;
    },
    doSomething: function() {
        // this must not be textboxElem
        alert(this);
        this.someElem.innerHTML = "123";
    }
};

回答1:


Copy the reference to a local variable, so that you can use it in a closure:

registerEvent: function() {
  var t = this;
  this.textboxElem.onkeydown = function() {
    t.doSomething();
  };
},


来源:https://stackoverflow.com/questions/6300817/event-handler-called-with-wrong-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!