这里不会导致每次调用Single.getInstance都重新new Single()吗?

let instance = null
这里不会导致每次调用Single.getInstance都重新new Single()吗?
因为先把instance赋值为null

Single.getInstance = (function() {
    let instance = null
    return function() {
        if(!instance) {
            instance = new Single()
        }
        return instance
    }
})()
阅读 1.3k
1 个回答

你这有个 IIFE 啊,最后实际返回的是里面的那个 function,instance 只会在 IIFE 执行时被声明一次。

近似等效于:

function foo() {
    let instance = null;
    
    Single.getInstance = function() {
        if(!instance) {
            instance = new Single()
        }
        return instance
    }
)

foo();

抛开 IIFE 不看的话就是:

let instance = null;

Single.getInstance = function() {
    if(!instance) {
        instance = new Single()
    }
    return instance
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题