Home > Web Front-end > JS Tutorial > How to solve the problem of this pointing to the bound element in the attachEvent function? _javascript skills

How to solve the problem of this pointing to the bound element in the attachEvent function? _javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 19:15:27
Original
988 people have browsed it

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.


[Ctrl A Select All Note: If you need to introduce external Js, you need to refresh to execute
]

[Ctrl A select all Note:
If you need to introduce external Js, you need to refresh to execute
]

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>
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template