js设计模式-单例模式

时间:2021-05-26 18:35:36
<!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>