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

1
  • 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 Commented Jul 29, 2013 at 12:21

1 Answer 1

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
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why not create function once outside of the for-loop?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.