如何正确地垃圾收集类实例数组?

时间:2016-09-01 19:14:17

标签: javascript class garbage-collection

我想使用以下代码来存储匿名类实例; cleanup()函数是确保在内存中没有任何东西悬空的正确方法吗?

var instances = [];

// example Class
function Ugh() {}

Ugh.prototype.stop = function() {
   // do stuff
};

// push some anonymous instances
instances.push(new Ugh());
instances.push(new Ugh());
instances.push(new Ugh());

// code I'm unsure of, is is correct?
function cleanup() {
  instances.forEach(function(item, i, arr) { 
    item.stop();
    arr[i] = null; // nullify the 'pointer'
  });
  instances.length = 0; // is this needed?
}

cleanup();

提前致谢。

0 个答案:

没有答案