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.pointerToFunandinstanceOfTestFunare two references to the same object.When you write
instanceOfTestFun = null, you’re changinginstanceOfTestFunto 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.