关于JS的内存泄漏跟JS代码的规范问题大家是怎么处理的?
比如这篇文章(JavaScript 中的内存泄露模式)中提到为防止内存泄露,把代码写成这样:
方法一:
<html> <body> <script type="text/javascript"> document.write("Avoiding a memory leak by adding another closure"); window.onload=function outerFunction(){ var anotherObj =function innerFunction() { // Some logic here alert("Hi! I have avoided the leak"); }; (function anotherInnerFunction(){ var obj = document.getElementById("element"); obj.onclick=anotherObj })(); }; </script> <button id="element">"Click Here"</button> </body> </html>
方法二:
<html> <head> <script type="text/javascript"> document.write("Avoid leaks by avoiding closures!"); window.onload=function() { var obj = document.getElementById("element"); obj.onclick = doesNotLeak; } function doesNotLeak() { //Your Logic here alert("Hi! I have avoided the leak"); } </script> </head> <body> <button id="element">"Click Here"</button> </body> </html>
方法一的代码明显比较乱,方法二很多人的写法都是写成匿名方法(方法表达式)的形式。
请问在JS的内存泄漏跟JS代码的规范间大家是怎么平衡的呢?
添加回答
举报
0/150
提交
取消