Web前端之路

JavaScript 单例模式

2019-07-04  本文已影响24人  _玖柒_

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

猜你喜欢

热点阅读