码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-06-04 20:44:36      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

<!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;
				}
				var singleInstance = null;
				//创建实例,info这是暴露在外面的
				var info = {
					createInstance: function() {
						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>

  

单例模式

标签:

原文地址:http://www.cnblogs.com/yqlog/p/5559414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!