Reference behavior for an object property

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

The same behavior is not replicated below.

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

Why is the above link copy behavior not applicable to the internal properties (property here) of an object?

objA.property = pointer1.property; β†’ do not refer to COPY?

+4
source share
1 answer

In case you set a reference to null, so no changes to the actual object

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

In the second case, you make changes to the object (changing the state of the object) by setting the property to null

 objA.property = null; 

therefore, in each link, the property value will be null

enter image description here

+3
source

Source: https://habr.com/ru/post/1492460/


All Articles