在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";
}
};
答案 0 :(得分:2)
将引用复制到局部变量,以便在闭包中使用它:
registerEvent: function() {
var t = this;
this.textboxElem.onkeydown = function() {
t.doSomething();
};
},