//方案一 var SingletonTester = (function () { //單例方法 function Singleton(args) { var args = args || {}; this.name = 'SingletonTester'; //方法對外的屬性,另一種方式就是返回對象 this.pointX = args.pointX || 6; this.pointY = args.pointY || 10; } //單例實例 var instance; //返回對象 return { name: 'SingletonTester', getInstance: function (args) { if (instance === undefined) { instance = new Singleton(args); } return instance; } }; })(); //直接執行該方法 //測試 var test = SingletonTester.getInstance({ pointX: 5 }); console.log(test.pointX);
function Universe() { // 判斷是否存在實例 if (typeof Universe.instance === 'object') { return Universe.instance; } // 其它內容 this.start_time = 0; this.bang = "Big"; // 緩存 Universe.instance = this; // 隱式返回this } // 測試 var uni = new Universe(); var uni2 = new Universe(); console.log(uni === uni2); // true