var func = function() { alert(1); };
Here a new function is created and a reference to it is copied to func
var func_alias = func;
The function reference stored is func
is assigned to another variable func_alias
var 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 in func
is lost. But since you saved it in func_alias
before overwriting func
, it can still be called.
func_alias();
func_alias
was 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:
var obj = {prop: 'val'};
Here, a new object is created and a reference to it is assigned to obj
var obj_alias = obj;
The reference is copied to another variable obj_alias
obj.prop = 'updated val';
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 of obj
(i.e. reference to the object created in first step) remains intact.
In your function example, you were actually overwriting the variable func
with a new function reference.
alert(obj_alias.prop);
The value of obj_alias
as well as that of obj
is 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 0x0001
When you assign it to obj_alias
, obj_alias
also gets the value 0x0001 - now both variables point to something stored at address 0x0001
When you do obj.x = y
, you aren't overwriting the value of obj
, but only using obj
to access the object stored at 0x0001 and modifying one of its properties.