问题
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