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.prototype
does point to a different object after the function is redefined, as I expected.__proto__
. That's what I don't understand.Could anyone explain, please?
It's a singleton pattern. The first time Universe is created the Universe symbol is redefined. (It still exists in a sort of limbo, though: the instance has some reference to it. __proto__
in non-strict mode for instance. )
The new Universe symbol isn't actually a constructor, it just returns the first created instance. The new keyword in the second call creates a new instance with the second Universe as prototype, but the new function just ignores it and returns the stored first instance instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With