0

In nodes terminal:

> o={a:1}                                                                                                                                                                        
{ a: 1 }                                                                                                                                                                         
> p=o        //set p=o(if I change anything in p or o, it reflects to the references                                                                                                                                                                    
{ a: 1 }                                                                                                                                                                         
> p=null     //but  setting p=null                                                                                                                                                                         
null                                                                                                                                                                             
> o                                                                                                                                                                              
{ a: 1 }     //don't set o to null

So I ask, why this happen, and more important, through one reference(or the original) can I delete every reference to that memory location?

So this way, I can delete 'o' when doing something to p?

Thanks

2 Answers2

1

why this happens

References and objects are different things. You reassigned p to point to null (conceptually). That did not affect other references.

through one reference(or the original) can I delete every reference to that memory location?

Nope, that is not possible.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

Why this happens:

p and o are technically not objects, they are references to an object. The object exists as long as at least one reference to it exists.*

When you set p to null, you're simply changing p so that it no longer references the same object as o - you're changing the value of the reference, not the value of the object. There is no mechanism by which you can get rid of all references to the object except to set each reference individually to null.

You could, however, use any reference to delete all the properties on the object, e.g. you could do:

delete p.a;

which would make o reference a now-empty object.

*It's a little more complex than that, as modern JavaScript engines can and do garbage-collect circular references correctly.

PMV
  • 2,058
  • 1
  • 10
  • 15