我在JavaScript中使用以下Singleton模式:
var exampleClass =(function(){
//private
var a ="test";
function PrivateMethod()
{
return a;
}
//public
return{
Test: function() {
alert(PrivateMethod());
}
}
})();
当我通读StackOverflow时,我看到了许多其他的Singleton实现,我开始怀疑我是否能够让自己变得更好。 我希望有人能告诉我这样做是对是错。
答案 0 :(得分:3)
这取决于您想要实现的目标,因为不同的实现将有不同的好处和限制。
最简单的实现只是一个对象文字:
var singleton = {
property: "foo",
method: function() {
alert('bar');
}
}
您在问题中提到的实现允许通过将方法封装在闭包中并返回应该公开的内容来实现公共和私有方法。
这是一个替代方案,类似地允许公共和私有方法,并且更具可扩展性:
function MySingletonClass() {
if ( arguments.callee._singletonInstance )
return arguments.callee._singletonInstance;
arguments.callee._singletonInstance = this;
this.Foo = function() {
// ...
}
}
var a = new MySingletonClass()
var b = MySingletonClass()
Print( a === b ); // prints: true
答案 1 :(得分:1)
这是我的。
差异是:
改进是:
所有函数都可以访问私有和公共函数(因为默认情况下所有函数都是私有的)
var exampleClass =(function(){
//private
var a ="test";
//declare here all functions
//(both for pass jslint validation and is good to have a list
//of all available functions, in case of classes with a lot of code
var PrivateMethod,
Test1,
Test2;
PrivateMethod = function()
{
return a;
};
Test1 = function()
{
return PrivateMethod();
};
Test2 = function()
{
return Test1();
};
//public
//Expose function you want to have pubblic
return{
Test1: Test1,
Test2: Test2
}
})();
答案 2 :(得分:0)
我正在使用这种模式:
var SingletonConstructor;
(function() {
var instance;
SingletonConstructor = function() {
if (typeof instance !== 'undefined')
return instance;
var a = "a";
function PrivateMethod() {
return a;
}
return instance = this;
};
})();
答案 3 :(得分:0)
Google Closure就是这样做的:
http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/base.js#427
答案 4 :(得分:0)
我喜欢以下模式:
function MyClass(){
if(MyClass.instance){
return MyClass.instance;
}
MyClass.instance = this;
//constructor code goes here
}
var a = new MyClass();
var b = new MyClass();
console.log(a == b); //true