Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 console output of testObj, but I see testFun function. I thought javascript uses 'pass by ref' for objects.

Please...advise me...

like image 991
Moon Avatar asked Jan 18 '23 04:01

Moon


2 Answers

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

When you write instanceOfTestFun = null, you're changing instanceOfTestFun to point to nothing.
This does not affect testObj.pointerToFun, which still refers to the original object.

If you change the original object (eg, instanceOfTestFun.name = "bye"), you will see the change through both accessors, since they both point to the (now-changed) object.

like image 97
SLaks Avatar answered Jan 21 '23 14:01

SLaks


You don't destroy the object itself if you set a property that holds a reference to it (instanceOfTestFun) to null. You can only indirectly destroy an object by removing the last reference to it (which is, at that point, the value held by testObj.pointerToFun), so it will be garbage-collected.

Under no circumstance can you delete a property of testObj without referencing it.

Don't confuse properties (instanceOfTestFun, testObj, testObj.pointerToFun) with the values they can hold (references to properties, as after testObj.pointerToFun = instanceOfTestFun, or plain values, as 9 or null).

like image 24
Jo So Avatar answered Jan 21 '23 15:01

Jo So