0
<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()

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.