我有以下代码:
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()
中对象实例的引用?
最佳答案
像这样...
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
}
}
关于javascript - 在事件处理程序中访问对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17922647/