Given functions in JavaScript are a reference type (copied by reference, unlike simple types), what precisely is going on here?
var func = function() { alert(1); };
var func_alias = func;
var func = function() { alert(2); };
func_alias(); //1
If func_alias is a reference to func, why is it non-updating? Wouldn’t you expect its invocation (line 4) to return 2?
This is different behaviour from other by-reference examples:
var obj = {prop: 'val'};
var obj_alias = obj;
obj.prop = 'updated val';
alert(obj_alias.prop); //updated val - not original one
func_alias seems to have kept a copy of the original, pre-overwrite func – in short, it seems to behave as though it’s copied it by value. This of course is disproven by:
var func = function(){}
var func_alias = func;
func === func_alias; //true
var func = function() { alert(1); };Here a new function is created and a reference to it is copied to
funcvar func_alias = func;The function reference stored is
funcis assigned to another variablefunc_aliasvar func = function() { alert(2); };Another new function is created and a reference to it is assigned to
func. The reference to the first function stored infuncis lost. But since you saved it infunc_aliasbefore overwritingfunc, it can still be called.func_alias();func_aliaswas assigned a reference to the first function in step 2 (and wasn’t overwritten after that point). So the first function is called.EDIT #1
As per your second example using an object:
Here, a new object is created and a reference to it is assigned to
objThe reference is copied to another variable obj_alias
Here you are not overwriting the value of
obj, but only overwriting a property of the object pointed to by that reference stored in obj. The value ofobj(i.e. reference to the object created in first step) remains intact.In your function example, you were actually overwriting the variable
funcwith a new function reference.The value of
obj_aliasas well as that ofobjis still the same, since you haven’t overwritten either. They both hold a reference to the object created in step 1.EDIT #2
This can maybe be explained well in C terms.
When you create an object via
var obj = {prop: 'val'};– lets say the object is stored at address 0x0001 in memory. i.e. the actual value of obj is 0x0001When you assign it to
obj_alias,obj_aliasalso gets the value 0x0001 – now both variables point to something stored at address 0x0001When you do
obj.x = y, you aren’t overwriting the value ofobj, but only usingobjto access the object stored at 0x0001 and modifying one of its properties.