Module pattern vs. instance of an anonymous constructor

前端 未结 4 2070
醉话见心
醉话见心 2021-02-01 17:09

So there\'s this so-called module pattern for creating singletons with private members:

var foo = (function () {
    var _foo = \'private!\';
    return         


        
4条回答
  •  独厮守ぢ
    2021-02-01 17:45

    More-or-less, they give you the same result. It's just a matter of which path you want to take for it.

    The 1st may be more popular since it's simply the mixture of 2 already common patterns:

    (function closure() {
        var foo = 'private';
        /* ... */
    }())
    
    var singleton = {
        bar : 'public'
    };
    

    However, prototype chaining would be the benefit of the 2nd pattern since it has its own constructor.

    var singleton = new function Singleton() { };
    assert(singleton.constructor !== Object);
    
    singleton.constructor.prototype.foo = 'bar';
    assert(singleton.foo === 'bar');
    

提交回复
热议问题