单例模式

本文介绍了一种使用JavaScript实现单例模式的方法,通过具体实例展示了如何创建唯一的对象实例,并确保所有对象都可通过同一入口访问该实例。同时,还展示了两个全局变量间的交互方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值