单例模式
1.
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();
2.
function Universe() { // 判断是否存在实例 if (typeof Universe.instance === 'object') { return Universe.instance; } // 其它内容 this.start_time = 0; this.bang = "Big"; // 缓存 Universe.instance = this; // 隐式返回this }
3.
function Universe() { // 缓存的实例 var instance = this; // 其它内容 this.start_time = 0; this.bang = "Big"; // 重写构造函数 Universe = function () { return instance; }; }
4.
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; }
5.
var Universe; (function () { var instance; Universe = function Universe() { if (instance) { return instance; } instance = this; // 其它内容 this.start_time = 0; this.bang = "Big"; }; } ());