Clearing objects from Javascript array
Possible Duplicate:
how to empty an array in JavaScript
Best way to deallocate an array of array in javascript
I have an array of objects:
var arr = [complexObj1, complexObj2];
If I want to clear the array and ensure that there is no memory leak, will the following do it?
arr.length = 0;
Or do I need to iterate through my array and call something like:
complexObj.release(); or
arr[0] = null; or
delete arr[0];
?
If the array consists of simple objects without references to other methods or DOM elements then all of the above solutions are enough.
If, however, the array contains objects that in turn holds references to event handlers that you have attached to DOM elements the object will not be destroyed when you clear the array.
var Complex = function(nodeId){
this.node=document.getElementById(nodeId);
this.handler=function(e){alert('wohooo'};
this.node.addEventListener('click', this.handler);
}
var myArray = [new Complex('buttonOne'), new Complex('buttonTwo')];
If you now 'reset' the array using myArray = []
. The array will be cleaned up but the objects still hold a node and a live event handler which will trigger when the buttons are clicked, meaning the object can't be removed from memory. You just lost a reference to it by removing from the array.
Your first thought was correct in that you should somehow 'destroy' the complex object and remove any references it holds.
Complex.prototype.release = function() {
this.node.removeEventListener('click',this.handler);
delete this.handler;
delete this.node
}
You now loop through the array and call release on the objects to remove the event listeners from the node.
This is a simple example of what I think people usually miss. It doesn't have to be event handlers either but can be anything that is referenced outside of the complex object.
只需重新初始化数组:
arr = [];
你需要做的只是
arr = null
链接地址: http://www.djcxy.com/p/23946.html
下一篇: 清除Javascript数组中的对象