Object copied to second property via reference persists even after original property deleted?

前端 未结 6 1880
情话喂你
情话喂你 2020-12-31 00:39

I thought objects are passed as reference. But when I delete b, it still exists in c. Please see this example:

This first part makes sense

6条回答
  •  情深已故
    2020-12-31 01:42

    ...I am late to the party? Here is my take on explaining it (Read the other answers as well, this is just to support those answers with a visual representation):

    1. Initialization of the empty object a with another object (value:true).

    enter image description here

    1. Assigning the empty object a with a property b referring to the other object (value:true).

    enter image description here

    1. Assigning the object a with a property c referring to the same object (value:true).

    enter image description here

    1. Deletion of the key b, thus a.b no longer refers to the sub-object (value:true).

    enter image description here

    1. Final representation of the main object a.

    enter image description here

    So we can easily see by visual representation how the sub-object was being preserved :)

提交回复
热议问题