Access object instance inside an event handler

两盒软妹~` 提交于 2019-12-10 15:59:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!