好吧,首先我知道一個對象沒有引用它的容器,除非明確定義,所以我在這裏尋找工作。訪問一個對象的父母
看看下面的代碼(從我的使用情況下,大量簡化了可讀性):
var cid = 0;
var Command = function(c) {
this.id = cid += 1;
this.transient = false;
return this;
}
var sid = 0;
var CommandSet = function() {
this.id = sid += 1;
this.commands = [];
this.transients = 0;
return this;
}
CommandSet.prototype.parent = null;
CommandSet.prototype.recurse = function(callback) {
callback.call(this);
if (this.parent instanceof CommandSet) {
this.parent.recurse(callback);
}
}
CommandSet.prototype.createSubset = function() {
var set = new CommandSet();
set.parent = this;
set.commands = this.commands;
set.transients = this.transients;
return set;
}
CommandSet.prototype.addCommand = function(c) {
if (c instanceof Command) {
this.commands.push(c);
if (c.transient) {
this.recurse(function() {
this.transients++;
});
}
}
return this;
}
CommandSet.prototype.toggleTransient = function(c) {
if (c instanceof Command) {
c.transient = true;
this.recurse(function() {
this.transients++;
});
}
return this;
}
如果我那麼做了以下(http://jsfiddle.net/5KGd8/1/):
var s1 = new CommandSet();
var c1 = new Command();
var c2 = new Command();
s1.addCommand(c1).addCommand(c2);
var s2 = s1.createSubset();
var s3 = s1.createSubset();
s2.toggleTransient(c1);
console.log(s1);
console.log(s2);
console.log(s3);
s1
現在有1個瞬態,s2
現在有1個瞬態,但s3
仍然沒有,儘管包含對同一個Command
對象的引用。
可能的解決方案:
我可以建立一個引用到其中存儲所有 套它位於內部,通過這些迭代每個命令,然而這 會導致一些嚴重的內存問題作爲我 應用的真正本質要求的子集可以被垃圾收集(用戶 將匿名經常創造出很多人沒有意識到),這將保留 引用他們,他們已經使用了。
parent
引用是好的,因爲我希望父設置存在,只要它有一個倖存的子集。我可以明確地強制用戶在 子集運行刪除功能時,它是沒有必要這將刪除它的所有內部參考的時間,但對於 他們這種複雜的事情,我喜歡的東西,自動將工作。我的應用程序的本質意味着我希望用戶創建子集時,他們甚至可能沒有意識到他們已經這樣做(通過創建和執行子集的其他功能)。
任何人都可以想出一種方法來解決這個問題,而沒有我的兩個解決方案中描述的問題?
你爲什麼從被稱爲構造函數的函數中返回這個''' –
@BenjaminGruenbaum沒有理由......沒有理由。 –
好的,只是爲了澄清 - 你想根據它所屬的所有超集來確定一個命令的瞬態數量(不確定這意味着什麼)? –