JS单例模式

2019/03/02 js

单例模式

在面向对象语言中,调用一个类的方法之前,必须先将这个类实例化,才能调用类方法。

单例模式能使得我们不需要每次都需要实例化一次,因为我们使用的对象都是同一个对象。

单例模式:只允许实例化一次的对象类。

JS的单例模式

const log = console.log;

let Leader = (()=>{
    let _instance = null;
    //一个待实例化的类
    function _module(){
        this.name = 'xxx';
        this.callLeader = ()=>{
            return 'The Leader Is ' + this.name;
        }
        this.setLeader = (name) => {
            this.name = name;
        }
    }

    return {
        getInstance:()=>{
            if(!_instance){
                _instance = new _module();
            }
            return _instance;
        }
    }
})();

Leader返回一个包含getInstance方法的对象,执行这个方法可以获得_module的实例。

let leader_01 = Leader.getInstance();
leader_01.setLeader('hhh');

let leader_02 = Leader.getInstance();
log(leader_02.callLeader())

log(leader_01 === leader_02);   //true

eader_01与leader_02完全相等,说明它们是同一个对象,并不是通过new新获取的对象。

但是在多页面情况下,通过import引入的并不是单例模式,因为

用途

模态框弹窗的时候,不希望有两个弹窗

Show Disqus Comments

Search

    Post Directory