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

前端 未结 6 1872
情话喂你
情话喂你 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:24

    That's because:

    The delete operator removes a property from an object. MDN Delete

    The entry b that corresponds to the Object {val: true} is removed from a. The entry c in a still refers to this object. If you try deleting c.val or a.b.val, you can still see the effect cascading to the other.

    What you're trying to do, i.e, deallocating data and expecting it to be cascaded across, doesn't happen in javascript. If you have a C++ background, consider thinking of all javascript objects as being reference counted. Ican remove a reference to it (i.e, the entry that 'points' to this object), but I can't remove the object itself. That is the pure prerogative of the javascript engine.

提交回复
热议问题