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...
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With