I understand that in Javascript, variables are always assigned by reference which means that if I write :
var a = {};
var b = a;
b.foo = 'string';
console.log(a.foo); // prints 'string'
Right, so writing the following code returns an error:
var a = function(){};
var b = function(){};
b.foo=a;
a.bar = b;
console.log(a); // prints { [Function] bar: { [Function] foo: [Circular] } }
This is ok, for a.bar points to b and b.foo points to a, whose .bar parameter points again to b and so on. This is a circular reference.
Now, I noticed the following thing :
var a = function(){};
var b = function(){};
b.foo=a;
a.prototype = b;
console.log(a); // prints [Function]
I just replaced a.bar with a.prototype and now, I’ve got no circular reference error.
I presume this means that Object.prototype cannot be assigned a value by reference. Can anyone confirm? Is this an exception to the rule (at least if it is true there is one)?
Thank you !
No, that seems to be only a anomaly of your console. In which browser do you encounter this? Opera’s Dragonfly for example won’t list any properties on functions.
Also, I haven’t seen a console that whinges about circular references in a logged object…
Yet, the circular reference is there also in your second example. Just try to print
b.foo.prototype.foo.prototype.foo...🙂 It only won’t be displayed as such, because the “prototype” property of functions is not enumerable (see spec 13.2, #18).