var mySingleton = (function () { var instance; functioninit() { functionprivateMethod() { console.log("I am private"); } var privateVariable = "Im also private"; var privateRandomNumber = Math.random(); return { publicMethod : function () { console.log("The public can see me!"); }, publicProperty : "I am also public", getRandomNumber : function () { return privateRandomNumber; } }; };
return { getInstance : function () { if (!instance) { instance = init(); } return instance; } }; })();
var singleA = mySingleton.getInstance(); var singleB = mySingleton.getInstance(); console.log(singleA === singleB);
** ES6 **
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classLeader { constructor () { if (!Leader.single) { this.level = 'supreme'; Leader.single = this; } returnLeader.single; } toString() { console.log('I am a leader.'); } }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>单例模式</title> </head> <body> <h1>单例模式</h1> <button id="loginBtn">登录</button> <script> var getSingle = function (fn) { var result; return function () { return result || (result = fn.apply(this, arguments)); } };
var createLoginLayer = function () { var div = document.createElement('div'); div.innerHTML = '我是登录悬浮窗'; div.style.display = 'none'; document.body.appendChild(div); return div; };
var createSingleLoginLayer = getSingle(createLoginLayer);
var createSingleIframe = getSingle(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); return iframe; });
// document.getElementById('loginBtn').onclick = function () { // var loginLayer = createSingleLoginLayer(); // loginLayer.style.display = 'block'; // };
document.getElementById('loginBtn').onclick = function () { var loginLayer = createSingleIframe(); loginLayer.src = 'http://baidu.com'; }; </script> </body> </html>