事件处理程序调用错误的上下文

时间:2011-06-10 00:37:29

标签: javascript javascript-events

SomeObj对象中,onkeydown事件处理程序this.doSomething在错误的上下文(textbox元素的上下文)中调用,但需要在this的上下文中调用它。怎么办呢?

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 个答案:

答案 0 :(得分:2)

将引用复制到局部变量,以便在闭包中使用它:

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