解决使用attachEvent函数时,this指向被绑定的元素的问题的方法


使用attachEvent对同一事件进行多次绑定,这是解决事件函数定义冲突的重要方法。但是在IE中,函数内的this指针并没有指向被绑定元素,而是function对象,在应用中,这是很难受的一件事,如果试图用局部变量传送元素,会因为闭包而引起内存泄漏。那么,我们应该如何解决这一难题呢?

我给Function添加了原型方法“bindNode”,在这个方法里,根据传送过来的元素,进行全局性存储转换,然后返回经过封装的函数,使用call方法来进行属主转换。



<html>
<body>
<button id=btTest>test</button>
</body>
</html>
<script>
if(!document.all){
HTMLElement.prototype.attachEvent=function(sType,foo){
this.addEventListener(sType.slice(2),foo,false)
}
}
Function.prototype.bindNode=function(oNode){
var foo=this,iNodeItem

//使用了全局数组__bindNodes,通过局部变量iNodeItem进行跨函数传值,如果直接传送oNode,也将造成闭包
if(window.__bindNodes==null)
__bindNodes=[]
__bindNodes.push(oNode)
iNodeItem=__bindNodes.length-1
oNode=null
return function(e){
foo.call(__bindNodes[iNodeItem],e||event)
}
}
abc()
function abc(){
var bt=document.getElementById("btTest")
bt.attachEvent("onclick",function(){

//如果不经过bindNode处理,下面的结果将是undefined
alert(this.tagName)
}.bindNode(bt))
bt=null
}
</script>
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3