【发布时间】:2013-07-12 13:53:30
【问题描述】:
我有一个 Javascript 垃圾收集/内存泄漏问题。我在 OS X 10.8.4 上使用 Chrome 28.0.1500.71。
以下代码永远不会释放 me 持有的空间,我不知道为什么。
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 会丢弃构造函数范围内的变量(new MyClass() 调用中的self)。
我也尝试过使用 Underscore.JS 的 _.bind 函数,但遇到了此处描述的相同未解决问题:Instances referenced by 'bound_this' only are not garbage collected。
【问题讨论】:
-
请准确区分“全局变量
me”和“MyClass对象”。该变量肯定会保留在内存中,但这不是问题(如果是,您可以将其从window中删除,请参阅 simonleung 的回答)。 Chrome 是否表明MyClass对象仍然存在? -
公平点;这是
me引用的MyClass对象,它永远不会被释放。我更新了问题的措辞以使这一点更清楚。 -
看起来 V8 中存在错误,我为此打开了一个问题:code.google.com/p/v8/issues/detail?id=2791
标签: javascript google-chrome memory-leaks garbage-collection google-chrome-devtools