当前位置: 首页 > 图文教程 > 网络编程 > Javascript > try finally 妙用,防止内存泄漏

Javascript
用js实现终止浏览器对页面HTML的继续解析即停止解析 兼容firefox
Auntion-TableSort国人写的一个javascript表格排序的东西
javascript实现二分查找法实现代码
利用ASP发送和接收XML数据的处理方法与代码
兼容ie和firefox的鼠标经过(onmouseover和onmouseout)实现--简短版
javascript之文本框输入四个数字自动加空格的脚本
比较简单实用的使用正则三种版本的js去空格处理方法
比较简洁的JavaScript 实时显示时间的脚本 修正版
JavaScript检查表单是否为空的函数
window.open被浏览器拦截后的自定义提示效果代码
javascript跟随鼠标的文字带滚动效果
让插入到 innerHTML 中的 script 跑起来的代码
Flash+XML滚动新闻代码 无图片 附源码下载
javascript(js) join函数使用方法介绍
表格头固定而列可滚动的效果
document.designMode的功能与使用方法介绍
精解window.setTimeout()&window.setInterval()使用方式与参数传递问题!
用javascript实现的电信铁通(网通)自动跳转源代码
用js查找法实现当前栏目的高亮显示的代码
javascript之鼠标拖动位置互换效果代码

Javascript 中的 try finally 妙用,防止内存泄漏


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 142 ::
收藏到网摘: n/a

预防内存泄漏
点击运行可以看到效果:
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]

这种写法在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 全选 提示:你可先修改部分代码,再按运行]