解決使用attachEvent函數(shù)時,this指向被綁定的元素的問題的方法
更新時間:2007年08月13日 19:14:35 作者:
使用attachEvent對同一事件進行多次綁定,這是解決事件函數(shù)定義沖突的重要方法。但是在IE中,函數(shù)內(nèi)的this指針并沒有指向被綁定元素,而是function對象,在應(yīng)用中,這是很難受的一件事,如果試圖用局部變量傳送元素,會因為閉包而引起內(nèi)存泄漏。那么,我們應(yīng)該如何解決這一難題呢?
我給Function添加了原型方法“bindNode”,在這個方法里,根據(jù)傳送過來的元素,進行全局性存儲轉(zhuǎn)換,然后返回經(jīng)過封裝的函數(shù),使用call方法來進行屬主轉(zhuǎn)換。
<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
//使用了全局?jǐn)?shù)組__bindNodes,通過局部變量iNodeItem進行跨函數(shù)傳值,如果直接傳送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(){
//如果不經(jīng)過bindNode處理,下面的結(jié)果將是undefined
alert(this.tagName)
}.bindNode(bt))
bt=null
}
</script>
我給Function添加了原型方法“bindNode”,在這個方法里,根據(jù)傳送過來的元素,進行全局性存儲轉(zhuǎn)換,然后返回經(jīng)過封裝的函數(shù),使用call方法來進行屬主轉(zhuǎn)換。
<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
//使用了全局?jǐn)?shù)組__bindNodes,通過局部變量iNodeItem進行跨函數(shù)傳值,如果直接傳送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(){
//如果不經(jīng)過bindNode處理,下面的結(jié)果將是undefined
alert(this.tagName)
}.bindNode(bt))
bt=null
}
</script>
相關(guān)文章
js 去掉空格實例 Trim() LTrim() RTrim()
js 去掉空格實例Trim(),LTrim(),RTrim() 需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01