参考资源:深入理解javascript系列 by Uncle Tom
单例就是保证一个类只有一个实例,实现的方法一般是先判断实例存在与否,如果存在直接返回,如果不存在就创建了再返回,这就确保了一个类只有一个实例对象。
对象字面量是最简单的单例模式:
var mySingleton = { property: "a property", method: function () { console.log("this is a method"); } };
一个简单的单例
var mySingleton = (function () { var instance, init = function () { return { property: "a property", method: function () {} }; }; return { getInstance: function () { return instance || (instance = init()); } }; })(); var mysingle = mySingleton.getInstance();
另一个单例
var mySingleton = (function () { var Singleton = function (args) { var args = args || {}; this.name = "a singleton"; this.pointX = args.pointX || 6; this.pointY = args.pointY || 10; }; var instance; var exports = { getInstance: function (args) { if (instance === undefined) { instance = new Singleton(args); } return instance; } }; return exports; })(); var mysingle = mySingleton.getInstance({ pointX: 10, pointY: 10 });
时间: 2024-09-29 18:00:33