单例模式: 保证一个类只有一个实例
最简单的实现方式, 就是使用对象字面量的方法
- let testSingleton_1 = {
- pt_1: 'test1',
- pt_2: 'test2',
- testFunc: function() {console.log('最简单的单例模式');
- }
- }
如果遇到这样的需求, 你要使用自己的私有变量和方法, 你可以使用闭包来封装这些属性和函数, 只暴露出你的公有变量和方法
- let testSingleton_2 = {
- let p_1 = '私有变量';
- function testFunc() {
- console.log('我是私有方法', p_1);
- }
- // 暴露出的对象, 你在里面可以定义你的想要给别人看到的东西
- return {
- p_2: '公有变量',
- testFunc_2: function() {
- console.log('公有方法');
- testFunc();
- }
- }
- }
当然我们前端是非常注重效率的, 所以我们要做到使用的时候才初始化
- let testSingleton_3 = (function() {
- let instance;
- let p_1 = '私有变量';
- function testFunc() {
- console.log('我是私有方法', p_1);
- }
- function init() {
- // 操作你的需求逻辑
- return {
- p_2: '公有变量',
- testFunc_2: function() {
- console.log('公有方法');
- testFunc();
- }
- }
- }
- return {
- getInstance: function() {
- if(!instance) {
- instance = init();
- }
- return instance;
- }
- }
- })();
直到这里我们的单例模式就已经说完了, 单例模式的宗旨就是保持一个类只有一个实例, 常用于原生 js 组件, jQuery 组件的开发, 更多使用场景可以自行 Google.
来源: http://www.qdfuns.com/article/16817/5179aac7f4ca094015c135b6b7cad4e5.html