设置this.constructor = this会导致循环引用/内存泄漏

时间:2011-08-17 13:25:30

标签: javascript oop memory-leaks constructor circular-reference

以下代码有效,但是我是否存在导致循环引用或内存泄漏的风险?

/* core package */
var core = function() {
    // Throw an error, the core package cannot be instantiated.
    throw new Error('A package cannot be instantiated.');
};

core.Container = function (properties){
    this.constructor = this;
    this.id = null;
    if ('id' in properties)
        this.id = properties['id'];
    else 
        throw new Error('A container must have an id.');
}
core.Container.prototype = new Object();

var container = new core.Container({'id': 'container'});
alert(container instanceof core.Container); // Result is true

2 个答案:

答案 0 :(得分:0)

分配

core.Container.prototype = new Object();

new core.Container 实例被指定为Object作为其构造函数 -

这个只引用构造函数本身,其构造函数应该是Function。

分配core.Container.prototype.constructor=core.Container

答案 1 :(得分:0)

由@Raynos在chat

中发布
  

@Utilitron取决于泄漏的含义我们是在谈论泄漏   IE6中不错的引擎或泄漏代码在v8中不应泄漏

相关问题