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

k5hmc34c  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(94)

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";
    }
};
qq24tv8q

qq24tv8q1#

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

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

相关问题