参考资源:深入理解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});
新闻热点
疑难解答