JavaScript - 单例类是什么样的?

时间:2013-02-26 07:11:41

标签: javascript singleton

我有2个Obj:我想知道如果他们是Singleton?

一个。

var OBJ = function () {
}

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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?