合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
## 单例模式 * 一个类只有一个实例 * 全局都可以访问 1. 实现Storage,使得该对象为单例,基于 localStorage 进行封装。实现方法 setItem(key,value) 和 getItem(key)。 ``` class StorageBase { } StorageBase.prototype.getItem = function (key) { localStorage.getItem(key) } StorageBase.prototype.setItem = function(key, value) { localStorage.setItem(key, value) } const Storage = (function() { let instance = null return function() { if(!instance){ instance = new StorageBase() } return instance } })() ``` 问题:Storage 为什么要用立即执行函数 答: 是为了能够让 instance 变量变成 Storage 的私有变量,外部访问不到。闭包是为了不让 instance 销毁