關于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代碼的規范間大家是怎么平衡的呢?
關于JS的內存泄漏跟JS代碼的規范問題大家是怎么處理的?
HUX布斯
2018-12-07 12:19:31