Tôi có câu hỏi nhanh về việc thêm/xóa người nghe của đối tượng DOM. Tôi muốn hỏi liệu bộ thu gom rác có thể thu thập bộ nhớ khi xóa các phần tử khỏi trang hay không.thêm/xóa người nghe trên javascript (bộ thu gom rác)
ví dụ: một thẻ <ul>
với một danh sách vài trẻ em (<li>
)
var ul = document.getElementById('someParent');
var children = ul.children;
var someFunction = function() {};
for(var i = 0; i < children.length; i++) {
children[i].addEventListener('click', someFunction);
}
// This is where I am not sure, would the garbage collector be able to collect
// the memory allocated on adding listener on children,
// if I remove the ul tag?
ul.remove();
Vòng lặp của bạn sẽ không hoạt động chính xác. 'children.length' không phải là điều kiện tốt. – Luka
chỉ là lỗi đánh máy, sẽ chỉnh sửa nó nhờ :) – olanchuy