傳統 OOP 中單例確保「類只有一個實例」;在 JavaScript 中,單例更多作為「命名空間提供者」,從全域提供唯一存取點,避免全域變數汙染。
var mySingleton = {
property1: "something",
property2: "something else",
method1: function() { console.log('hello world'); }
};
var mySingleton = function() {
var privateVariable = 'something private';
function showPrivate() { console.log(privateVariable); }
return {
publicMethod: function() { showPrivate(); },
publicVar: 'the public can see this!'
};
}();
var single = mySingleton();
single.publicMethod(); // 輸出 'something private'
var Singleton = (function() {
var instantiated;
function init() {
return {
publicMethod: function() { console.log('hello world'); },
publicProperty: 'test'
};
}
return {
getInstance: function() {
if (!instantiated) instantiated = init();
return instantiated;
}
};
})();
Singleton.getInstance().publicMethod();
var SingletonTester = (function() {
function Singleton(args) {
args = args || {};
this.name = 'SingletonTester';
this.pointX = args.pointX || 6;
this.pointY = args.pointY || 10;
}
var instance;
return {
getInstance: function(args) {
if (instance === undefined) instance = new Singleton(args);
return instance;
}
};
})();
var singletonTest = SingletonTester.getInstance({ pointX: 5 });
console.log(singletonTest.pointX); // 5
function Universe() {
if (typeof Universe.instance === 'object') return Universe.instance;
this.start_time = 0; this.bang = "Big";
Universe.instance = this;
}
var u1 = new Universe(), u2 = new Universe();
console.log(u1 === u2); // true
function Universe() {
var instance = this;
this.start_time = 0; this.bang = "Big";
Universe = function() { return instance; };
}
var u1 = new Universe(), u2 = new Universe();
u1.bang = "123"; console.log(u2.bang); // "123"
function Universe() {
var instance;
Universe = function Universe() { return instance; };
Universe.prototype = this;
instance = new Universe();
instance.constructor = Universe;
instance.start_time = 0; instance.bang = "Big";
return instance;
}
// 測試原型屬性共享
Universe.prototype.nothing = true;
var u1 = new Universe();
Universe.prototype.everything = true;
var u2 = new Universe();
console.log(u1.nothing, u2.everything); // true true
var Universe;
(function() {
var instance;
Universe = function Universe() {
if (instance) return instance;
instance = this;
this.start_time = 0; this.bang = "Big";
};
})();
var a = new Universe(), b = new Universe();
console.log(a === b); // true
JavaScript 單例模式實作多樣,核心在於「控制實例化入口」與「緩存實例引用」。實務上推薦方式三(惰性初始化)或方式四(最佳實踐),結構清晰、支援參數配置、且不汙染全域。視專案複雜度選擇最適合的版本。