考慮以下幾點:強迫生活在內存中的對象指向不同的對象?
var obj1 = {"value":"one"};
var obj2 = obj1;
console.log(obj2.value+"\n"); // prints "one"
obj1 = {"value":"two"};
console.log(obj2.value+"\n"); // still prints "one"
我明白這樣做的原因,在頭兩行,obj1
和obj2
是引用這都指向同一個對象,{"value":"one"}
,地方在內存中。當obj1
被分配給不同的對象時,{"value":"two"}
,obj2
仍然指向內存中相同的對象{"value":"one"}
。
我在尋找的是一種強制內存中的{"value":"one"}
對象將其呼叫者重定向到{"value":"two"}
對象的方法。換句話說,我正在尋找一種方式來操縱{"value":"one"}
對象,以使obj2
變量將最終指向{"value":"two"}
對象,不重新分配obj2
變量:
var obj1 = {"value":"one"};
var obj2 = obj1;
console.log(obj2.value+"\n"); // prints "one"
// ...some code to manipulate the `{"value":"one"}` object in memory
// so that *any* references which originally pointed to the
// `{"value":"one"}` object now point to the `{"value":"two"}`
// object, like a sort of "redirection". This would be done
// without ever explicitly reassigning the references.
console.log(obj2.value+"\n"); // now prints "two"
有沒有辦法做到這一點?
實際應用涉及到一些非常複雜的Mozilla代碼這將妨礙這個線程嘗試和解釋,所以我問這是一個一般的理論問題。
編輯:結論:
「否」是最正確的答案實際問題,下面狀態torazaburo的評論這一點。不過,我覺得帕特里克的答案,使用代理,最接近完成這一點,所以我接受了他的答案。我會補充一點,雖然代理是非常強大的工具,但它們與實際的目標對象並不相同,並且存在一些限制。
這是對象身份的一個基本問題。一個對象本身就是,而且永遠是。對於您的潛在問題,可能有其他解決方案,但即時更改對象的身份 - 從其下方更換對象 - 不是其中的一個。 – 2016-07-28 19:48:04
很容易獲得'console.log(obj2()。value +「\ n」);'如上所述運作。你可能可以使用getter或者proxy來避免這些parens .... – dandavis