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; } return Leader.single; } toString() { console.log('I am a leader.'); } }
const leader = new Leader(); const leader1 = new Leader(); console.log(Object.is(leader, leader1)); // true
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>