其他分享
首页 > 其他分享> > 【每日一个成长小技巧】前端单例模式

【每日一个成长小技巧】前端单例模式

作者:互联网

TS写法

//单例模式
class Demo {
    private static instance: Demo;
    private constructor(public name:string){

    }
    static getInstance(name:string){
        if(!this.instance){
            this.instance = new Demo(name)
        }
        return this.instance
        
    }
}

const demo1 = Demo.getInstance("zhangsan");
const demo2 = Demo.getInstance("lisi");

console.log(demo1.name)     //zhangsan
console.log(demo2.name)     //zhangsan
console.log(demo1===demo2)  //true

ES6写法

//es6
class Demo{
    constructor(name){
        this.instance = null;
        this.name = name;
    }

    static getInstance(name){
        if(!this.instance){
            this.instance = new Demo(name)
        }
        return this.instance
    }
}

const demo1 = Demo.getInstance("zhangsan");
const demo2 = Demo.getInstance("lisi");

console.log(demo1.name)     //zhangsan
console.log(demo2.name)     //zhangsan
console.log(demo1===demo2)  //true

ES5写法

//es5
function Demo(name){
    this.name = name;
    this.instance = null
}
Demo.getInstance = function(name){
    if(!this.instance){
        this.instance = new Demo(name)
    }
    return this.instance;
   
}

var demo1 = Demo.getInstance("zhangsan");
var demo2 = Demo.getInstance("lisi");

console.log(demo1.name)     //zhangsan
console.log(demo2.name)     //zhangsan
console.log(demo1===demo2)  //true

标签:技巧,getInstance,Demo,前端,instance,log,单例,zhangsan,name
来源: https://blog.csdn.net/weixin_43188138/article/details/123210775