2013-02-26 80 views
0

我有2個Obj:我想知道如果他們是Singleton?JavaScript - 什麼是單例類?

a。

var OBJ = function() { 
} 

OBJ.prototype = { 
    setName : function (name) { 
     this.name = name; 
    }, 
    getName : function() { 
     return this.name; 
    } 
} 

b。

var OBJ = { 
    setName : function (name) { 
     this.name = name; 
    }, 
    getName : function() { 
     return this.name; 
    } 
} 
+0

可能重複?我不會繼續編輯它。 – Blender 2013-02-26 07:13:52

+0

@Blender我不知道我不能在代碼中創建第二個塊。我不知道爲什麼我看不到工具欄並預覽它。 – Anar 2013-02-26 07:15:14

+0

這將是有幫助的:http://www.hardcode.nl/subcategory_1/article_526-singleton-examples-in-javascript.htm – cclerville 2013-02-26 07:20:36

回答

1

您可以通過創建類的兩個實例檢查,並進行比較:

Print(a === b); // prints: true 

如果打印true類是singleton

或者你可以嘗試SingletonPattern驗證碼:

function MyClass() { 

    if (arguments.callee._singletonInstance) 
    return arguments.callee._singletonInstance; 
    arguments.callee._singletonInstance = this; 

    this.Foo = function() { 
    // ... 
    } 
} 

var a = new MyClass() 
var b = MyClass() 
Print(a === b); // prints: true 

Best Solution For Singleton Pattern

0

這將幫助你How to write a singleton class in javascript

function Cats() { 
    var names = []; 

    // Get the instance of the Cats class 
    // If there's none, instanciate one 
    var getInstance = function() { 
     if (!Cats.singletonInstance) { 
      Cats.singletonInstance = createInstance(); 
     } 
     return Cats.singletonInstance; 
    } 
    // Create an instance of the Cats class 
    var createInstance = function() { 
     // Here, you return all public methods and variables 
     return { 
      add : function(name) { 
       names.push(name); 
       return this.names(); 
      }, 
      names : function() { 
       return names; 
      } 
     } 
    } 
    return getInstance(); 
} 

更多關於http://www.javascriptkata.com/2009/09/30/how-to-write-a-singleton-class-in-javascript/

此外,它可以是你能正確地格式化你的問題的Javascript: best Singleton patternSimplest/Cleanest way to implement singleton in JavaScript?