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

Javascript
javascript prototype的深度探索不是原型继承那么简单
兼容Firefox和IE的onpropertychange事件oninput
javascript兼容firefox的文本输入长度提示
js字符编码函数区别分析
js程序中美元符号$是什么
javascript 数组的方法集合
javascript编程必备_JS语法字典
javascript动画效果打开/关闭层
javascript键盘事件全面控制脚本代码
javascript键盘上下键的操作(选择)
JavaScript容错例外处理
js将网址转为urlencode类型
JScript中使用ADODB.Stream判断文件编码的代码
[原创]js循环输出图片,不足的要补0
js left,right,mid函数
javascript 网站常用的iframe分割
javascript下兼容firefox选取textarea文本的代码
JSON学习笔记
asp.net和asp下ACCESS的参数化查询
JavaScript入门学习书籍推荐

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 155 ::
收藏到网摘: 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 全选 提示:你可先修改部分代码,再按运行]