Access Object Instance Inside An Event Handler
I have the following code: var myObj = { inputs: document.getElementsByTagName('input'), attachKeyEvent: function() { for ( var i = 0; i < this.inputs.length; i++ ) {
Solution 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
}
}
Post a Comment for "Access Object Instance Inside An Event Handler"