try finally 妙用,防止內(nèi)存泄漏
更新時(shí)間:2008年03月31日 18:55:55 作者:
預(yù)防內(nèi)存泄漏
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
這種寫法在IE中100%內(nèi)存泄漏
使用try finally很容易解決些問題
復(fù)制代碼 代碼如下:
function createButton(){
var obj = document.createElement("button");
obj.innerHTML="點(diǎn)我!";
obj.onclick=function(){
//處理click事件
}
obj.onmouseover=function(){
//處理mouseover事件
}
try{
return obj;
}finally{
obj = null;//這句話在return 之后才執(zhí)行,有效地解決了需在return后將obj置null的問題
}
}
一個(gè)函數(shù)或方法中,其實(shí)有很多地方都需要這種選返回值,最后執(zhí)行某些事的
=====================================================================
附一:JavaScript Error (try/catch/finally)
Introduction
Like other programming languages, JavaScript provides the possibility to make use of
the try/catch/finally block. Usually when an error is encountered then the script stops and doesn't
continue with the rest of the page. The try/catch/finally block can be used to continue the
processing with the rest of the page. You just have to put the code in your try block and when
an error in encountered there, then it will call the catch block. The finally block is called always
regardless of an error occurred or not. The following example makes the usage clear.
Example:
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
相關(guān)文章
js拖動(dòng)div 當(dāng)鼠標(biāo)移動(dòng)時(shí)整個(gè)div也相應(yīng)的移動(dòng)
要拖動(dòng)的div為最外層的div,這段代碼對(duì)顯示對(duì)話框的頭部綁定鼠標(biāo)監(jiān)聽事件,當(dāng)鼠標(biāo)移動(dòng)時(shí),整個(gè)div也相應(yīng)的移動(dòng),具體的實(shí)現(xiàn)如下,感興趣的朋友可以參考下2013-11-11
HTML5附件拖拽上傳drop & google.gears實(shí)現(xiàn)代碼
從gmail 的附件拖拽上傳,到網(wǎng)易郵箱的拖拽上傳,我們看到了html 5 為我們帶來了新的web體驗(yàn)。2011-04-04
javascript運(yùn)算符——邏輯運(yùn)算符全面解析
下面小編就為大家?guī)硪黄猨avascript運(yùn)算符——邏輯運(yùn)算符詳解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
js動(dòng)態(tài)修改input輸入框的type屬性(實(shí)現(xiàn)方法解析)
本文是對(duì)js動(dòng)態(tài)修改input輸入框的type屬性的實(shí)現(xiàn)方法。進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2013-11-11
利用ASP發(fā)送和接收XML數(shù)據(jù)的處理方法與代碼
利用ASP發(fā)送和接收XML數(shù)據(jù)的處理方法與代碼...2007-11-11

