【问题标题】:Singleton Pattern in JavascriptJavascript 中的单例模式
【发布时间】:2012-11-15 05:59:26
【问题描述】:

我最近在阅读Javascript Patterns。当下面的代码谈到单例模式时,我不明白:

function Universe(){
    var instance;
    Universe=function Universe(){
        return instance;
    };
    Universe.prototype=this;

    //the new Universe below,refers to which one?The original one,
    //or the one:function(){return this;} ??
    instance=new Universe();

    instance.constructor=Universe;

    instance.bang="Big";

    return instance;
}
Universe.prototype.nothing=true;
var uni=new Universe();
Universe.prototype.everything=true;
var uni2=new Universe();

uni===uni2;//true

【问题讨论】:

  • 您对这个例子有什么具体问题?
  • 这看起来不必要的复杂......我会使用其他模式。
  • @FelixKling 我肯定会使用其他方式,例如使用闭包。我只是不明白代码,所以我问你们......

标签: javascript design-patterns singleton


【解决方案1】:

这里没有太多事情发生。主要关注点应该是构造函数,它会为你返回一个实例化的 Universe。所以任何调用它的人都会引用同一个实例。注意构造函数是如何指向 Universe 函数的。

我不会使用这种模式,因为 new 关键字意味着正在创建一个新实例,而且我的口味似乎有点太深奥了。在 JS 中,你可以完美地拥有一个对象字面量,通常与命名空间模式一起使用:

(function(ns, window, undefined) {
    ns.singleton = {
        bang: 'Big'
    };

    window.ns = ns;
})(ns || {}, window);

console.log(window.ns.singleton.bang === 'Big');

当然,这不是一个真正的单例,但它不需要实例化,任何使用它的人都会有相同的值。

更多单例实现见Javascript: best Singleton pattern

【讨论】:

    【解决方案2】:

    你的代码很乱。

    我会使用这种模式:

    var universe = function(){
    
      var bang = "Big"; //private variable
    
      // defined private functions here    
    
      return{  //return the singleton object 
        everything : true,
        // or nothing : true, I don't guess your logic
    
        // public functions here (closures accessing private functions and private variables)
        getBang : function(){ return bang; } 
      };
    }();
    

    然后您可以调用例如:

    alert(universe.everything); // true
    alert(universe.getBang()); //true
    alert(universe.bang); //Undefined property ! Cause private ;)
    

    由于它是一个单例,因此无需为prototype 对象定义共享方法,因为会有一个实例。 (因此是函数表达式而不是函数声明)。

    这种设计的所有优点都在于作用域链和闭包(公共函数)的好处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 2014-12-26
      • 1970-01-01
      相关资源
      最近更新 更多