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

发布于 2024-11-30 04:38:46 字数 613 浏览 1 评论 0原文

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

/* 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

The following code works, but am I running the risk of causing circular reference or a memory leak?

/* 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

聽兲甴掵 2024-12-07 04:38:46

当您分配

core.Container.prototype = new Object();

new core.Container 时,实例被分配为 Object 作为其构造函数

- this 仅指构造函数本身,其构造函数应为 Function。

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

when you assign

core.Container.prototype = new Object();

new core.Container instances are assigned Object as their constructor-

this only refers to the constructor function itself, whose constructor should be Function.

Assign core.Container.prototype.constructor=core.Container

肩上的翅膀 2024-12-07 04:38:46

正如@Raynos 在聊天中发布的那样

@Utilitron 取决于你所说的泄漏是什么意思,我们是在谈论泄漏吗?
不错的引擎或 IE6 中的泄漏该代码不应在 v8 中泄漏

As posted by @Raynos in chat

@Utilitron depends what you mean by leaks are we talking leaks in
decent engines or leaks in IE6 That code shouldnt leak in v8

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文