【问题标题】:Design pattern - Singleton pattern in JavaScript设计模式 - JavaScript 中的单例模式
【发布时间】:2021-08-19 03:51:42
【问题描述】:

我正在关注这个article。我了解单例模式是什么,但我无法理解代码。

let Singleton = (function(){
    let instance = null;

    function createInstance() {
        let obj = new Object("I am the new instance");
        return obj;
    }

    return {
        getInstance:function() {
            console.log(instance);
            if(instance === null) {
                instance = createInstance();
            }
            return instance;
        }
    }
})();

function test() {
    let instance1 = Singleton.getInstance();
    let instance2 = Singleton.getInstance();
    console.log(Object.is(instance1,instance2));
}
test();

为什么instance1 和instance2 相同,我们总是将实例初始化为null,每当我们调用Singleton

【问题讨论】:

    标签: javascript design-patterns singleton


    【解决方案1】:

    每当我们调用 Singleton 时,我们总是将实例初始化为 null。

    你没有。 Singletonreturn语句中的对象,不包括let instance = null语句。该语句只执行一次;此变量在返回对象 (Singleton.getInstance) 的 getInstance 方法中的 closure 下捕获。代码相当于

    let instance = null;
    
    function createInstance() {
        let obj = new Object("I am the new instance");
        return obj;
    }
    
    let Singleton = {
        getInstance: function() {
            console.log(instance);
            if (instance === null) {
                instance = createInstance();
            }
            return instance;
        }
    }
    

    除了instancecreateInstance 隐藏在IIFE 的范围内。

    您可以通过插入更多日志语句来验证let instance = null 执行了多少次(以及何时)。

    【讨论】:

    • 知道了,我将 Singleton 解释为一个函数,但实际上是一个具有 getInstance 属性的对象。谢谢阿马丹。
    猜你喜欢
    • 1970-01-01
    • 2017-10-12
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多