我正在嘗試創建對象a的副本,而無需手動將其屬性輸入到對象b中。在這個代碼中,b簡單地指的是a。我想創建一個新版本的a,所以當我向b添加一個屬性時,它通過a不可見。JavaScript:如何製作一個對象的副本?
var a = new Object(); // create an empty object
var b = a; // now b refers to the same object
b.test = 1; // add a new property to b
alert(a.test); // => 1: the new property is also visible through a
a === b; // => true: a and b refer to the same object
'存儲a的值(b)應該是「將同一對象的引用賦值給'b'」。 – RobG
你真的打算'a'是一個函數嗎?您在該行的評論意味着其他情況。 –
「b指向同一對象」意味着「向b添加新屬性」等於「向a添加新屬性」。 「 – leaf