try finally 妙用,防止內(nèi)存泄漏
更新時間: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="點我!";
obj.onclick=function(){
//處理click事件
}
obj.onmouseover=function(){
//處理mouseover事件
}
try{
return obj;
}finally{
obj = null;//這句話在return 之后才執(zhí)行,有效地解決了需在return后將obj置null的問題
}
}
一個函數(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)文章
JavaScript Date對象詳解及時間戳和時間的相互轉(zhuǎn)換問題
這篇文章主要介紹了JavaScript Date對象詳解及時間戳和時間的相互轉(zhuǎn)換問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01JS自調(diào)用匿名函數(shù)具體實現(xiàn)
定義一個函數(shù)用做臨時的命名空間,在這個命名空間內(nèi)定義的變量都不會污染到全局命名空間,需要的朋友可以參考下2014-02-02JS當(dāng)前頁面登錄注冊框,固定DIV,底層陰影的實例代碼
下面小編就為大家?guī)硪黄狫S當(dāng)前頁面登錄注冊框,固定DIV,底層陰影的實例代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09如何利用Promises編寫更優(yōu)雅的JavaScript代碼
如何利用Promises編寫更優(yōu)雅的JavaScript代碼?下面小編就為大家?guī)硪黄肞romises編寫更優(yōu)雅的JavaScript代碼。希望對大家有所幫助。一起跟隨小編過來看看吧2016-05-05