在Javascript中理解单例对象

时间:2014-11-13 09:12:13

标签: javascript function singleton

我无法理解实例调用new Universe()时会发生什么。它不仅仅是返回" 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;
}

1 个答案:

答案 0 :(得分:1)

它不会返回undefined而不是它将返回object.see在警告框或控制台中;

 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());