javascript 单例模式应用

单例模式

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';
 }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值