Closure (Đóng gói)
Inner function truy cập biến outer function. Memory leak xảy ra khi biến outer được giữ trong closure scope dù inner function không dùng đến nó.
Ví dụ closure cơ bản
<html> <body> <script> window.onload = function parentFunction(arg1) { var a = arg1; return function childFunction(arg2) { alert(a + " " + arg2); }; }; var val = parentFunction("outer val"); val("inner val"); </script> </body> </html>
Khi parentFunction trả về childFunction, scope chứa a được giữ lại (closure) → không GC được.
Cách tránh memory leak
Thêm function trung gian (break closure chain)
Tạo 2 inner function, không function nào trực tiếp tham chiếu outer variable → closure bị ngắt.
Ví dụ
<html> <body> <script> window.onload = function parentFunction(){ var Obj1 = function childFunction1() { document.write("the leak is avoided"); }; (function childFunction2(){ var obj2 = document.getElementById("closure"); obj2.onclick = Obj1; })(); }; </script> <input type="button" id="closure" value="Click Here"> </body> </html>
Kết quả: click button → in "the leak is avoided". Không còn closure giữ scope outer.