• 单例模式


    <!DOCTYPE html>
    <html>
    
    	<head>
    		<meta charset="UTF-8">
    		<title></title>
    		<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    
    		<script>
    		     /*单例模式 就是方便 模块间的相互调用*/
    			// 外层函数只是为了自动执行,创建函数实例
    			var xw = (function xiaoWang() {
    				//创建类方法
    				var sendMessage = function() {
    					var infoClass = {
    						setLian: function() {
    							this.lian = "大脸";
    							return this;
    						},
    						setZui: function() {
    							this.zui = "大嘴";
    							return this;
    						}
    					}
    					return infoClass;
    				}
    				//创建实例,info这是暴露在外面的,相当于OBJECT-C中的static类变量
    				var info = {
    					createInstance: function() {
    						var singleInstance = null;
    						if (!singleInstance) {
    							singleInstance = new sendMessage();
    						}
    						return singleInstance;
    					}
    				}
    				return info;
    			})();
    			(function xiaoLi() {
    				msg = xw.createInstance().setLian().setZui();
    				console.log(msg);
    				msg = null;
    			}());
    		</script>
    	</head>
    
    	<body>
    		<button id="btna">按钮a</button>
    		<button id="btnb">按钮b</button>
    		<script>
    			/*-------------单例模式也可以是 两个全局变量-----------*/
    			var aInstance = {
    				init: function() {
    					this.render();
    					this.binder();
    				},
    				a: 4,
    				render: function() {
    					var me = this;
    					me.btna = $('#btna');
    				},
    				binder: function() {
    					var me = this;
    					me.btna.click(function() {
    						me.test();
    					});
    				},
    				test: function() {
    					bInstance.b = 8;
    					console.log(bInstance);
    				}
    			}
    			
    			
    			var bInstance = {
    				init: function() {
    					this.render();
    					this.binder();
    				},
    				b: 4,
    				render: function() {
    					var me = this;
    					me.btnb = $('#btnb');
    				},
    				binder: function() {
    					var me = this;
    					me.btnb.on('click', (function() {
    						me.test();
    					}));
    				},
    				test: function() {
    					aInstance.a = 7;
    					console.log(aInstance);
    				}
    			}
    			aInstance.init();
    			bInstance.init();
    		</script>
    	</body>
    
    </html>
    

      

  • 相关阅读:
    js实现快速排序(in-place)简述
    手把手原生js简单轮播图
    基于superagent 与 cheerio 的node简单爬虫
    浅谈HTTP事务的一个过程
    css小技巧
    DesignPatternPrinciple(设计模式原则)二
    DesignPatternPrinciple(设计模式原则)一
    Attribute(特性)与AOP
    Thread(线程)四
    Thread(线程)三
  • 原文地址:https://www.cnblogs.com/yqlog/p/5559414.html
Copyright © 2020-2023  润新知