I saw the following code in the JavaScript Patterns book by Stoyan Stefanov (edited to remove extra fat):
function Universe() {
var instance = this;
Universe = function() {
return instance;
}
}
Universe.prototype.nothing = true;
var uni = new Universe();
Universe.prototype.everything = true;
var uni2 = new Universe();
uni.nothing; // true
uni2.nothing; // true, but I was expecting undefined
uni.everything; // undefined
uni2.everything; // undefined, but I was expecting true
I was expecting nothing to be assigned to the original function’s prototype, and everything to be assigned to the closure’s prototype (since the second assignment happens after redefinition). However, the output shows that something odd is going on, and the book really doesn’t explain it. I also noticed that:
Universe.prototypedoes point to a different object after the function is redefined, as I expected.- Further instances created after the redefinition still get the original prototype object as their
__proto__. That’s what I don’t understand.
Could anyone explain, please?
unianduni2are the same object because the value ofinstanceis returned in both versions of theUniversefunction.Here is the same code but without
instancereturned from the redefinedUniverse: http://jsfiddle.net/nmaBn/