JavaScript 单例模式


在很多情况下,我们需要全局使用某一个实例,这个时候我们可以使用单例模式来解决这个问题!
话不多说,直接上代码!老规矩,还是ES6规范

let Instance = null;
class Person {
    static getInstance() {
        if (!(Instance instanceof this)) {
            Instance = new this()
        }
        return Instance
    }
}
let a = Person.getInstance()
let b = Person.getInstance()
console.log(a === b); //true

你可能感兴趣的:(JavaScript 单例模式)