• 单例模式


    <!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>
    

      

  • 相关阅读:
    android 联系数据库
    shuffle一个简单的过程叙述性说明
    每天的学习经验:SharePoint 2013 定义自己添加的产品清单。Callout菜单项、文档关注、SharePoint服务机端对象模型查询
    函数调用
    InputMonitor注意事项
    处理FTP上传成功推理
    用Web技术开发客户端(一)
    简析Chrome和Webkit的渊源
    历史在重演:从KHTML到WebKit,再到Blink
    开发者应当了解的WebKit知识
  • 原文地址:https://www.cnblogs.com/yqlog/p/5559414.html
Copyright © 2020-2023  润新知