2013-07-20 129 views
4
var myObject = new Object(); 
var myObjectCopy = myObject; 

myObject.Name = 'alav'; 

// logs Name alav on both variable 
console.log(myObject, myObjectCopy); 

myObject = null; 

// logs myObject as null and myObjectCopy still has name 'alav' -> bcoz of reference copy 
console.log(myObject, myObjectCopy); 

下面不會複製相同的行爲。物件屬性的參考行爲

var objA = {property: 'value'}; 
var pointer1 = objA; 

// update the objA.property, and all references (pointer1 & pointer2) are updated 
objA.property = pointer1.property; 
objA.property= null; 
// logs 'null null' because objA, pointer1 all reference the same object 
console.log(objA.property, pointer1.property); 

爲什麼上述引用複製行爲不適用於對象的內部屬性(屬性here)?

objA.property = pointer1.property; - >是不是引用COPY?

+0

你意識到'var myObjectCopy = myObject;'沒有真正複製任何東西,它只是兩個引用到完全相同的對象? – adeneo

+0

是的當然是 –

+2

而對於答案,沒有「json對象」之類的東西,JSON是一個帶有鍵和值的數據格式,通常是雙引號,常規的javascript對象絕不是JSON。 – adeneo

回答

3

在情況下,一個你設定基準因此通過設置屬性設置爲null

空在實際對象

myObject = null;// setting reference to null object , but no change in actual object 

在你正在變化引入對象(改變對象的狀態) 第二情況下,不改變

因此在每一個參考,屬性值將是無效

enter image description here

+0

但是我不確定:( –

+0

你是如何準備這張圖表的?使用visio? –

+0

沒有使用MS powerpoint :) –