js设计模式-单例模式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单例模式</title>
</head>
<body>
<script>
    /* 模式的产生:在编码过程中 我们需要自定义一个类来不断new得到该对象的实例,
       但是我们希望,new出来的实例都是同一个对象
    */
    //es5的写法
    var Person1  = (function () {
        var _this = null;
        return function (name,age) {
            if(!_this){

                _this = this;
            }
            _this.name = name;
            _this.age = age;
            return _this
        }
    })();
    var person11 = new Person1("A",18);
    console.log("姓名:"+person11.name,"年龄:"+person11.age);
    var person22 = new Person1("B",19);
    console.log("姓名:"+person22.name,"年龄:"+person22.age);
    console.log(person11===person22); //==>true
    //es6的写法
    let Person = (function () {
        let _this = null;
        return class {
            constructor(name,age) {
                if (!_this) {
                    _this = this;
                }
                _this.name = name;
                _this.age = age;
                return _this;
            }
        }
    })()

    let person1 = new Person("A",18);
    console.log("姓名:"+person1.name,"年龄:"+person1.age);
    let person2 = new Person("B",19);
    console.log("姓名:"+person2.name,"年龄:"+person2.age);
    console.log(person1===person2); //==>true
</script>
</body>
</html>

 

转载于:https://www.cnblogs.com/jsydb/p/9590068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值