Home  >  Article  >  Web Front-end  >  The wonderful use of try finally to prevent memory leaks_javascript skills

The wonderful use of try finally to prevent memory leaks_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:05:281693browse

[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]

This way of writing is in IE 100% memory leak

It is easy to solve some problems using try finally The code is as follows:


function createButton(){
var obj = document.createElement("button");
obj.innerHTML="Click me!";
obj.onclick=function(){
//Handle click event
}
obj.onmouseover=function(){
//Handle mouseover event
}
try{
return obj;
} finally{
obj = null;//This sentence is executed after return, which effectively solves the problem of setting obj to null after return.
}
}



In a function or method, there are actually many places that require this kind of return value selection, and finally perform something

================== ================================================== ==
Appendix 1: 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 select all Note:
If you need to introduce external Js, you need to refresh to execute <script> function createButton(){ var obj = document.createElement("button"); obj.innerHTML="点我!"; obj.onclick=function(){ //处理click事件 } obj.onmouseover=function(){ //处理mouseover事件 } return obj;//这里由于需要返回创建的对象,所以不能把obj直接设为null. return 后obj是局部变量,不能在外部断开其与HTMLElement的引用.ie中将出现问题泄漏问题 } var 按钮 = document.getElementsById("d1").appendChild( createButton()); 按钮.做某些事(); 按钮.做某些事(); ........ 某些东西.某些事(按钮); ...... </script>]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn