0

I have the following code:

var instance;
function Universe() {
    return instance;
};
instance = new Universe();  

How come that instance is not undefined?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • 3
    What is the purpose of the code you've written? – Andy Apr 12 '16 at 15:19
  • 5
    The question is _What does `new` return?_ Answer: `object` – Tushar Apr 12 '16 at 15:19
  • @Andy I'd say the only purpose is to test the SO community and other JavaScript programmers. – E_net4 Apr 12 '16 at 15:19
  • "How come that instance is not undefined?" Because it is defined? – j08691 Apr 12 '16 at 15:21
  • 1
    If a `return` statement is executed in a function invoked with `new`, and the returned value is not an object reference, the returned value is ignored and the object instantiated as a side-effect of `new` is returned instead. – Pointy Apr 12 '16 at 15:21
  • http://www.ecma-international.org/ecma-262/5.1/#sec-13.2.2 – Rajaprabhu Aravindasamy Apr 12 '16 at 15:22
  • 1
    Javascript functions are objects. Even if you change your function to not return anything, the result will still be the same. – Alex Chance Apr 12 '16 at 15:24
  • I create a [jsfiddle](https://jsfiddle.net/dckch1br/) to test it, the `instance` isn't undefined. – Qianyue Apr 12 '16 at 15:26
  • See also [What is the 'new' keyword in JavaScript?](http://stackoverflow.com/q/1646698/1048572)/[How does the `new` operator/keyword work internally](http://stackoverflow.com/q/6750880/1048572) – Bergi Apr 12 '16 at 15:26
  • if you just called Universe() as a function, then it would return instance, but you're calling Universe() via new, so it's going to return a fresh object based on the prototype template defined by your Universe() function. – ManoDestra Apr 12 '16 at 15:30
  • 1
    @Pointy, in this case after the first call all other calls will return same instance of object, stored in `instance` variable. – Vasyl Moskalov Apr 12 '16 at 15:30
  • @VasylMoskalov yes, that is exactly correct. – Pointy Apr 12 '16 at 15:31
  • @ManoDestra. Nope! Only first call (or any other call to Universe in case of `instance` is not instance of Universe) return fresh object. In case of `instance` is instance of Universe any call to new Universe() will return same object, stored in instance variable. – Vasyl Moskalov Apr 12 '16 at 15:32
  • 1
    this is an implementation of a singleton pattern. thanks everyone for help – Max Koretskyi Apr 12 '16 at 15:35
  • @VasylMoskalov That is precisely what I stated above. It returns a new object **"based on the prototype template defined by your Universe() function"**. If instance has changed, since the first call, then clearly that would affect what the Universe() function then defines for the new object. – ManoDestra Apr 12 '16 at 16:05

0 Answers0