try finally 妙用,防止内存泄漏

(编辑:jimmy 日期: 2025/12/30 浏览:2)


[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
这种写法在IE中100%内存泄漏

使用try finally很容易解决些问题
复制代码 代码如下:
function createButton(){ 
 var obj = document.createElement("button"); 
 obj.innerHTML="点我!"; 
 obj.onclick=function(){ 
 //处理click事件 
 } 
 obj.onmouseover=function(){ 
 //处理mouseover事件 
 } 
 try{ 
 return obj; 
 }finally{ 
 obj = null;//这句话在return 之后才执行,有效地解决了需在return后将obj置null的问题 
 } 



一个函数或方法中,其实有很多地方都需要这种选返回值,最后执行某些事的

=====================================================================
附一: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需再刷新一下页面才能执行]
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?