对象属性的引用行为

时间:2013-07-20 10:48:29

标签: javascript

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);

为什么上述引用复制行为不适用于对象的内部属性(此处属性)?

objA.property = pointer1.property; - >不是参考COPY?

1 个答案:

答案 0 :(得分:3)

如果您正在设置对null的引用,因此实际对象中没有更改

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

在第二种情况下,您正在更改对象(更改对象的状态) 通过将property设置为null

objA.property = null; 

因此,在每个引用中,属性的值将为null

enter image description here