Why is this variable still alive?

I have the following source code.

testObj = {} function testFun() { this.name = "hi"; } function test () { var instanceOfTestFun = new testFun(); testObj.pointerToFun = instanceOfTestFun; instanceOfTestFun = null; console.log(testObj); } $(document).ready(test); 

I expected to see "null" for the output of the testObj console, but I see the testFun function. I thought javascript uses 'pass by ref' for objects.

Please ... advise me ...

+4
source share
3 answers

testObj.pointerToFun and instanceOfTestFun are two references to the same object.

When you write instanceOfTestFun = null , you change instanceOfTestFun to indicate nothing.
This does not affect testObj.pointerToFun , which is still related to the source object.

If you change the source object (for example, instanceOfTestFun.name = "bye" ), you will see the change through both accessors, since they both point to the object (now modified).

+7
source
 var x = {}; 

The above line creates an object and stores a reference to it inside the variable x .

 var y = x; 

The above line copies the link from the variable x to the variable y . Now both x and y contain references to the object.

 x = null; 

The line above removes the link that was stored inside x . The object referenced by this link does not collect garbage, since the variable y still contains a link to it.

Any given object lives as long as it refers to at least one link.

+1
source

You do not destroy the object itself if you set the property that contains the reference to it ( instanceOfTestFun ) to null . You can only indirectly destroy the object by deleting the last reference to it (that is, at that moment the value held by testObj.pointerToFun ), so it will be garbage collected.

Under no circumstances can you remove the testObj property without reference to it.

Do not confuse properties ( instanceOfTestFun , testObj , testObj.pointerToFun ) with the values ​​that they can hold (property references, like after testObj.pointerToFun = instanceOfTestFun or simple values ​​like 9 or null ).

+1
source

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


All Articles