<!DOCTYPE html> <html> <head> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> </head> <body> <script> var Single = (function () { var instance = null; var defaultData = {age: 25}; SingleInstance.prototype._init = function (ops) { for (var a in defaultData) { this[a] = defaultData[a]; } for (var b in ops) { this[b] = ops[b]; } }; function SingleInstance(args) { if (this instanceof SingleInstance) { if (instance == null) { instance = this; } instance._init(args); return instance; }else { if(instance==null){ instance=new SingleInstance; } instance._init(args); return instance; } } return SingleInstance; })(); var i1 = new Single({name: "xu"}); var i2 = new Single({name: "tong"}); var i3 = Single({name: "bao"}); console.log(i1 === i2); //true console.log(i1 === i3); //true console.log(i1.name); //bao console.log(i1.age); //25 </script> </body> </html>
js单例模式
猜你喜欢
转载自blog.csdn.net/xutongbao/article/details/80279407
今日推荐
周排行