问题
I have the following code:
var myObj = {
inputs: document.getElementsByTagName('input'),
attachKeyEvent: function() {
for ( var i = 0; i < this.inputs.length; i++ ) {
this.inputs[i].onkeypress = this.getChar;
console.log(this); // => returns ref to myObj
}
},
getChar: function(e) {
console.log(this); // => [Object HTMLInputElement]
// get a reference to myObj
}
}
I have a DOM structure with a couple of <input type="text" />
elements. I need to write a couple of methods to enhance the key press event.
How can I get reference to the object instance within getChar()
?
回答1:
Like this...
var myObj = {
inputs: document.getElementsByTagName('input'),
attachKeyEvent: function() {
var me = this;
var handler = function(){
me.getChar.apply(me, arguments);
}
for ( var i = 0; i < this.inputs.length; i++ ) {
this.inputs[i].onkeypress = handler;
console.log(this); // => returns ref to myObj
}
},
getChar: function(e) {
console.log(this); // => [Object HTMLInputElement]
// get a reference to myObj
}
}
来源:https://stackoverflow.com/questions/17922647/access-object-instance-inside-an-event-handler