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

Javascript
javascript删除Table中的一行的脚本代码
非常不错的[JS]Cookie精通之路
日历控件在FF2.0,ie6下测试可用
JavaScript 给汉字排序实例代码
js查找父节点的简单方法
js禁用和激活input表单的方法
js兼容标准的表格变色效果
js文字滚动停顿效果代码
js打字机效果代码
复制本贴标题和地址的js代码
js兼容IE6,IE7菜单高亮显示效果代码
Class Of Marquee Scroll通用不间断滚动JS封装类
不错的JavaScript面向对象的简单入门介绍
Javascript&DHTML基础知识
Javascript & DHTML DOM基础和基本API
Javascript & DHTML上传文件控件
javascript indexOf函数使用说明
用JS剩余字数计算的代码
javascript 火狐(firefox)不显示本地图片问题解决
Javascript入门学习第一篇 js基础

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


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