用JavaScript实现单例的最简单/最干净的方法?在JavaScript中实现单例模式的最简单/最干净的方法是什么?
3 回答
千巷猫影
TA贡献1829条经验 获得超7个赞
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};})();var test = SingletonFactory.getInstance();
慕容3067478
TA贡献1773条经验 获得超3个赞
模块模式:
var foo = (function () {
"use strict";
function aPrivateFunction() {}
return { aPublicFunction: function () {...}, ... };}());Foo
单例模式:
var Foo = function () {
"use strict";
if (Foo._instance) {
//this allows the constructor to be called multiple times
//and refer to the same instance. Another option is to
//throw an error.
return Foo._instance;
}
Foo._instance = this;
//Foo initialization code};Foo.getInstance = function () {
"use strict";
return Foo._instance || new Foo();}var Foo = (function () {
"use strict";
var instance; //prevent modification of "instance" variable
function Singleton() {
if (instance) {
return instance;
}
instance = this;
//Singleton initialization code
}
//instance accessor
Singleton.getInstance = function () {
return instance || new Singleton();
}
return Singleton;}());var a, b;a = new Foo(); //constructor initialization happens hereb = new Foo();console.log(a === b); //true
if (instance)
var a, b;a = Foo.getInstance(); //constructor initialization happens hereb = Foo.getInstance();console.log(a === b); //true
function Foo() {
if (Foo._instance) {
return Foo._instance;
}
//if the function wasn't called as a constructor,
//call it as a constructor and return the result
if (!(this instanceof Foo)) {
return new Foo();
}
Foo._instance = this;}var f = new Foo(); //calls Foo as a constructor-or-var f = Foo(); //also calls Foo as a constructor添加回答
举报
0/150
提交
取消
