4

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()?

gmajivu
  • 1,272
  • 2
  • 13
  • 21
  • i think the approach is not logical. You should not use a private method from outside the object itself. Instead, use a public `getChar` function – Sebas Jul 29 '13 at 12:21

1 Answers1

3

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
  }
}
mohkhan
  • 11,925
  • 2
  • 24
  • 27