Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to the prototype when a function redefines itself?

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:

  1. Universe.prototype does point to a different object after the function is redefined, as I expected.
  2. 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?

like image 446
bfavaretto Avatar asked Feb 17 '23 23:02

bfavaretto


1 Answers

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.

like image 169
Odalrick Avatar answered Feb 20 '23 12:02

Odalrick