设置 this.constuctor = this 会导致循环引用/内存泄漏
以下代码有效,但我是否面临导致循环引用或内存泄漏的风险?
/* 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您分配
new core.Container 时,实例被分配为 Object 作为其构造函数
- this 仅指构造函数本身,其构造函数应为 Function。
分配 core.Container.prototype.constructor=core.Container
when you assign
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
正如@Raynos 在聊天中发布的那样
As posted by @Raynos in chat