我有一个 Javascript 垃圾收集/内存泄漏问题。我在 OS X 10.8.4 上使用 Chrome 28.0.1500.71。
下面的代码从不解除分配由我
持有的空间,我不知道为什么。
var MyClass = function() {
this.x = 1;
var self = this;
this.do_thing = function() {
self.x++;
};
};
MyClass.prototype.destroy = function() {
delete this.do_thing;
};
var me = new MyClass();
me.do_thing();
me.destroy();
me = null;
// the MyClass object formerly known as 'me' is still allocated here
// (as evidenced by Chrome's heap profiler)
Chrome 似乎保留了由表达式 new MyClass()
创建的对象(me
在设置为 null
之前指向的对象) ) 在内存中,因为它在调用 me.do_thing()
时被 self
引用。但是,我原以为调用 destroy()
会取消设置 me.do_thing
会丢弃构造函数范围内的变量(self
在 new MyClass()
调用中)。
我也曾尝试使用 Underscore.JS 的 _.bind
函数,但遇到了此处描述的相同未解决问题:Instances referenced by 'bound_this' only are not garbage collected .
最佳答案
我不知道为什么它没有被垃圾回收,但是将 destroy 方法添加到实例而不是原型(prototype)并将 self
设置为 null,显然会起作用:
var MyClass = function() {
this.x = 1;
var self = this;
this.do_thing = function() {
self.x++;
};
this.destroy = function() {
delete this.do_thing;
self = null;
};
};
var me = new MyClass();
me.do_thing();
me.destroy();
me = null;
关于JavaScript 关闭内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17641726/