标签:
<!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