Using attachEvent to bind the same event multiple times is an important way to resolve conflicting event function definitions. But in IE, the this pointer in the function does not point to the bound element, but the function object. In the application, this is a very uncomfortable thing. If you try to use local variables to transfer elements, it will cause closure errors. Memory leak. So, how should we solve this problem?
I added the prototype method "bindNode" to Function. In this method, global storage conversion is performed based on the passed elements, and then the encapsulated function is returned, and the call method is used to perform owner conversion.
It won’t cause closure Of course it will happen, please use drip to test
http://www.script8.com/download/drip.rar<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><script> abc() function abc(){ var bt=document.getElementById("btTest") bt.attachEvent("onclick",function(){ //如果不经过bindNode处理,下面的结果将是undefined alert(bt.tagName) }) } </script>