<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()
-
Check this out stackoverflow.com/questions/16316954/…Samy– Samy2013年07月10日 06:23:25 +00:00Commented Jul 10, 2013 at 6:23
2 Answers 2
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.
Comments
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)