根据mdn documentation,方法removeChild
从DOM中删除一个节点,但它仍然驻留在内存中。
我的问题是我也想从内存中删除它。
我试过delete
运算符,但对象仍在那里......
myCanvas.parentElement.removeChild(myCanvas); // myCanvas actually removed from DOM
delete myCanvas; // false. does nothing
alert(myCanvas); // shows HTMLCanvasElement instead of undefined
答案 0 :(得分:8)
阅读http://perfectionkills.com/understanding-delete/。删除操作符不适用于变量(这就是它返回false
的原因)。
如果要删除变量对DOM节点的引用,请使用
myCanvas = null;
覆盖该值。通常你永远不需要这样做,因为JS的垃圾收集器会为你完成所有的工作。
答案 1 :(得分:3)
只需为myCanvas
变量分配另一个值(如null
),这样就不会有更多变量引用canvas元素。垃圾收集将完成其余的工作。
当然,没有保证。这假设没有其他变量引用该元素。否则,如果有其他变量,仍然引用该canvas元素的对象等,则它根本不会从内存中删除。如果存在包含对元素的引用但无法解除引用的闭包,则会更难删除。
答案 2 :(得分:0)
好吧,如果您在没有myCanvas
关键字的情况下初始化var
变量,那么您的代码段可能会有效,因为这些变量会自动变为configurable: true
,因此可以使用{{1操作员没有任何麻烦。
或者,您可以使用delete
方法处理对象引用,而不是使用个人getElementsByClassName()
本身
- 我在此假设HTMLElement
是myCanvas
操作之类的结果 -
因为getElementById()
生成的HTMLCollection
将自动更新,并在从树中删除后立即删除对该DOM对象的任何引用。
换句话说,它本质上是 live ,因此它不需要任何手动操作来破坏/清除引用。
答案 3 :(得分:0)
The basic answer is that all variables referencing the canvas need to be set to undefined
so that the garbage collector can do its job. But sometimes it's not so simple in practice.
Here are several tricky situations I came across when trying to completely remove dynamically-created HTML canvas elements to avoid memory leaks:
(1) Methods I had added to the canvas element held their own references to it (creating a cycle). I fixed this by deleting all custom properties when removing the canvas:
function deleteAllProperties(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
delete obj[key];
}
}
}
deleteAllProperties(myCanvas);
myCanvas = undefined;
(2) Internal variables in other objects still referenced the canvas. Fixed by setting them all to undefined
:
_myVar = myBuilder = myObserver = undefined;
(3) A variable referenced the canvas' context: var ctx = myCanvas.getContext('2d');
This held on to the canvas in some browsers (even after setting myCanvas = undefined
). Fixed by clearing that variable too:
ctx = undefined;