Reputation: 3037
<script>
//bob first initialization
var bob = function()
{
console.log('bob');
};
//set jan to bob via reference
var jan = bob;
//set bob to another function
bob = function()
{
console.log('newbob');
};
jan(); //console.logs 'bob'
bob(); //console.logs 'newbob'
</script>
Question:
why jan()
; outputs bob
, not newbob
? since jan()
is the reference of bob()
Upvotes: 0
Views: 37
Reputation: 883
jan and bob are just two variables that happened to point to the same function at one point in time, but the assignment of a new value to one of them doesn't have any effect on the value assigned to the other. It's like:
var a = 1;
var b = a; // a and b evaluate to 1
var a = 2; // a evaluates to 2, b evaluates to 1 (a's
// assignment has no effect on b)
Upvotes: 0
Reputation: 943097
After var jan = bob;
, both jan
and bob
are references to the same function.
bob = function() {}
assigns a reference to a new function to bob
jan
still contains a reference to the original function.
i.e. You are changing the value of the variable, you aren't changing the function that the variable referred to.
To compare:
var a = { f: function () { console.log(1); } };
var b = a;
a.f = function () { console.log(2); };
Now a
and b
contain references to the same object. The object contains a reference to a function. When you assign a new function to that object property the a.f
and b.f
both change because a
and b
are still both references to the same object.
Upvotes: 4