Home  >  Article  >  Web Front-end  >  How to solve the problem of this pointing to the bound element when using the attachEvent function_javascript skills

How to solve the problem of this pointing to the bound element when using the attachEvent function_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:10:461218browse

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.








<script> <BR>if(!document.all){ <BR> HTMLElement.prototype.attachEvent=function(sType,foo){ <BR> this.addEventListener(sType.slice(2),foo,false) <BR> } <BR>} <BR>Function.prototype.bindNode=function(oNode){ <BR> var foo=this,iNodeItem <br><br> //使用了全局数组__bindNodes,通过局部变量iNodeItem进行跨函数传值,如果直接传送oNode,也将造成闭包 <BR> if(window.__bindNodes==null) <BR> __bindNodes=[] <BR> __bindNodes.push(oNode) <BR> iNodeItem=__bindNodes.length-1 <BR> oNode=null <BR> return function(e){ <BR> foo.call(__bindNodes[iNodeItem],e||event) <BR> } <BR>} <BR>abc() <BR>function abc(){ <BR> var bt=document.getElementById("btTest") <BR> bt.attachEvent("onclick",function(){ <br><br> //如果不经过bindNode处理,下面的结果将是undefined <BR> alert(this.tagName) <BR> }.bindNode(bt)) <BR> bt=null <BR>} <BR></script>
Statement:
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