【JS】单例模式

来源:互联网 发布:淘宝店已下架什么意思 编辑:程序博客网 时间:2024/05/31 05:28

背景

在面向对象语言中,调用一个类的方法之前,必须先将这个类实例化,才能调用类方法。单例模式能使得我们不需要每次都需要实例化一次,因为我们使用的对象都是同一个对象。


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

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


总结

  • a.减少new的开销,获取的所有对象都为同一个
原创粉丝点击