0

I'm having trouble understanding what happens when the instance calls new Universe(). Doesn't it just return "undefined"?

function Universe() {
  var instance;

  Universe = function Universe() {
    return instance;
  }

  Universe.prototype = this;
  instance = new Universe();
  instance.constructor = Universe;
  instance.start_time = 0;
  instance.bang = "big";
  return instance;
}
mike
  • 43
  • 3
  • Check this: http://stackoverflow.com/questions/1635800/javascript-best-singleton-pattern It's an answer about which is the best way to implement Singleton in javascript – Michael Nov 13 '14 at 09:30

1 Answers1

1

it wont return undefined instead of that it will return object.see in alert box or in console;

 function Universe() {
          var instance;

          Universe = function Universe() {
            return instance;
          }

          Universe.prototype = this;
          instance = new Universe();
          alert("ins"+instance);//or
       console.log(instance);
          instance.constructor = Universe;
          instance.start_time = 0;
          instance.bang = "big";
          return instance;
        }

        alert(Universe());//or
console.log(Universe());
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
  • But, what about the instance in the newly declared Universe function. It does not define a value for instance, so why doesn't it return undefined when it invokes new Universe()? – mike Nov 14 '14 at 08:21
  • @mike initially it will be undefined only but later when you will use new Universe() it means you are asking for an object therefore the value returned will be converted into object hence you will not have undefined. – Suchit kumar Nov 14 '14 at 09:18