单例模式
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="btn">create</button>
</body>
</html>
js部分
//缺点:外部可以修改Test.instance
// function Test(name) {
// if(typeof Test.instance === 'object') {
// return Test.instance;
// }
// this.name = name;
// Test.instance = this;
// }
//缺点:失去了原型继承
// function Test(name) {
// const instance = this;
// this.name = name;
// Test = function() {
// return instance;
// }
// }
//完美的单例模式
// var Test = (function() {
// var instance;
// return function(name) {
// if(typeof instance === 'object') {
// return instance;
// }
// instance = this;
// this.name = name;
// }
// })();
// const t1 = new Test('huzhixin');
// Test.prototype.lastName = 'D';
// const t2 = new Test('huqiao');
// console.log(t1 === t2);
// const CreateElement = (function (text) {
// var el = null;
// return function(text) {
// if(el !== null) {
// return el;
// }
// el = document.createElement('div');
// el.textContent = text;
// el.style.display = 'none';
// document.body.appendChild(el);
// return el;
// }
// })();
// btn.onclick = function () {
// let el = new CreateElement('hello world');
// console.log(el);
// el.style.display = 'block';
// }
function createElement(text) {
var el = document.createElement('div');
el.textContent = text;
el.style.display = 'none';
document.body.appendChild(el);
return el;
}
const getSingle = function (fn) {
var result;
return function () {
if(!result) {
result = fn.apply(this,arguments);
}
return result;
}
}
const singleEl = getSingle(createElement);
btn.onclick = function() {
console.log(singleEl);
var ele = singleEl('hello huzhixin');
ele.style.display = 'block';
}