gpt4 book ai didi

javascript - 删除自变异对象的实例

转载 作者:行者123 更新时间:2023-11-29 21:55:11 26 4
gpt4 key购买 nike

拥有一个根据用户请求创建自身新实例的对象。我的问题是关于如何构造它,主要是如何正确删除实例。

基本上是这样的:

(function (something) {
var collection = {},
counter = -1;

function remove(ix) {
delete collection[ix];
}

function Foo() {
collection[++counter] = this;
this.index = counter;
this.load();
}
Foo.prototype.load = function () {
/* - Create some element and add it to DOM.
* - Add listeners for events.
* - If "New" is clicked call this.add()
* - If "Remove" is clicked call this.remove()
* */
};
Foo.prototype.add = function () {
var x = new Foo();
};
Foo.prototype.remove = function () {
/* - Remove listeners.
* - Remove element from DOM.
* */
remove(this.index);
};

something.Foo = Foo;
})(this);

var bar = new Foo();

“自行创建” 实例是否可以通过这种方法正确删除? (如将来某个时候收集的 GB 中。)有没有更好的方法来解决这个问题?

我可以说:

delete collection[ix];

remove() 函数中?或者,我是否必须在调用 remove() 时使用 setTimeout()?或者,...其他事情?

最佳答案

你做的很好。

执行 delete collection[ix]collection[ix] = null 两者都会消除对 collection[ix] 值的引用.

当然,如果您要枚举 collection 的属性,则使用 delete 会更好,因为该对象现在将从列表中删除。如果您只是将它设置为 null,该值仍将作为 collection 的属性存在:

设置为null:

collection["x"] = 1
collection["x"] = null;
console.log(collection)// { x: null }

删除:

collection["x"] = 1
delete collection["x"]
console.log(collection)// {}

关于javascript - 删除自变异对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26810901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com