單例模式

<!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>
相關文章
相關標籤/搜索