|
我給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>
JavaScript技術(shù):解決使用attachEvent函數(shù)時,this指向被綁定的元素的問題的方法,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。