In the following javascript code:
function foo() {
foo.val = foo.val || 'no val';
return 'foo has ' + foo.val;
};
function bar() {
bar.val = bar.val || 'no val';
return 'bar has ' + bar.val;
};
var a = foo;
foo.val = '1';
bar.val = '2';
a.val = '3';
foo = bar;
'foo says "' + foo() + '", bar says "' + bar() + '", a says "' + a() +'"';
what I would expect would be:
foo says “bar has 2”, bar says “bar has 2”, a says “foo has 3”
However, when run from the Firebug console in Firefox 10.0.2 I get:
foo says “bar has 2”, bar says “bar has 2”, a says “foo has 2”
Can anyone explain to me the sequence of events that goes on behind the scenes to make this so? Why does a stay bound to the original foo function (as I would expect) but hold bar‘s value for val?
After this line of code:
apoints to the same function thatfoopoints to. Inyou reassign
footo point to whateverbarrefers to. This doesn’t updatea‘s reference — it still points to the function thatfooalso originally pointed to.Now, when you run
a(), the original function is executed. It grabsfoo(which now points tobar‘s reference) and gets itsvalproperty. Thevalofbar‘s object is 2, so this is what is returned.It’s a bit difficult to explain in words.. would a diagram be easier to understand, perhaps?