JavaScript 关闭内存泄漏

标签 javascript google-chrome memory-leaks garbage-collection google-chrome-devtools

我有一个 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 会丢弃构造函数范围内的变量(selfnew 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/

相关文章:

memory-leaks - 图灵机中的内存泄漏,由 Free Pascal 编译

javascript - jquery/jqueryui,单击div中除按钮之外的任意位置

javascript - list.map 不是函数 help create-react-app

css - Chrome 设备模式模拟媒体查询不工作

google-chrome - 使用 Chrome 扩展将 CSS 注入(inject)文档检查器

c++ - 在此代码中找不到内存泄漏

grails - 简单Grails 2.5.1应用程序使用Groovy 2.4.4泄漏类加载器

javascript - 如何从字符串数组中删除逗号

javascript - 旧版本 jQueryUI AutoComplete 控件中的类别

css - 设置自动填充建议的样式