BIG陽
2019-06-27 16:10:44
用JavaScript實現(xiàn)單例的最簡單/最干凈的方法?在JavaScript中實現(xiàn)單例模式的最簡單/最干凈的方法是什么?
3 回答

千巷貓影
TA貢獻(xiàn)1829條經(jīng)驗 獲得超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貢獻(xiàn)1773條經(jīng)驗 獲得超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
提交
取消