这里不会导致每次调用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
}
推荐问题