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

问题描述

| 在“ 0”对象中,在错误的上下文中(文本框元素的上下文)调用了onkeydown事件处理程序“ 1”,但需要在“ 2”的上下文中调用它。如何才能做到这一点?
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\";
    }
};
    

解决方法

        将引用复制到局部变量,以便可以在闭包中使用它:
registerEvent: function() {
  var t = this;
  this.textboxElem.onkeydown = function() {
    t.doSomething();
  };
},