GitHub:codelegant/input-filter,Git@OSC:chuanfeng/input-filter。
attachEvent 中的 this
事件处理程序在事件目标上定义,所以它们作为这个对象的方法来调用并不出人意料。这就是说,在事件处理程序内,this关键字指的是事件目标。
但是,对于attachEvent()
来说,这是不对的:使用achEvent()
注册的处理程序作为函数调用,它们的 this 值是全局(Window)对象。
1 2 3 |
target.attachEvent("onclick",function(){ console.info(this);//并不是指代target,而是指代Window }); |
解决方案:
1 2 3 4 5 6 |
function eventHandler=function(){...} target.attachEvent("onclick",function(){ //把处理程序作为事件目标的方法调用 //传递事件对象 return eventHandler.call(target); }) |