在事件处理程序中访问对象实例

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
  }
}

我有一个带有几个 <input type="text" /> 元素的 DOM 结构。 我需要编写一些方法来增强按键事件。如何在 getChar() 内获得对象实例的引用?

我认为这种方法不太合理。你不应该从对象外部使用私有方法。相反,应该使用公共的 getChar 函数。 - Sebas
1个回答

3

就像这样...

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
  }
}

为什么不在for循环外创建函数? - Yury Tarabanko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接