Module pattern vs. instance of an anonymous constructor

前端 未结 4 2069
醉话见心
醉话见心 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:35

    In this case it seems you are using only one instance object of that "class". So may want to take look at what Douglas Crockford thinks about putting new directly in front of function:

    By using new to invoke the function, the object holds onto a worthless prototype object. That wastes memory with no offsetting advantage. If we do not use the new, we don’t keep the wasted prototype object in the chain. So instead we will invoke the factory function the right way, using ().

    So according to the renown javascript architect of Yahoo! you should use the first method, and you have his reasons there.

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2021-02-01 17:50

    Douglas Crockford writes about the second one. As Greg says in his comments, I thought it was quite common, and I've used it in the past.

    Edit: to actually answer your question - there's no downsides, the two are functionally equivalent (both create a closure containing the "private variables" and exposing other variables/methods publically), and have exactly the same browser support and performance characteristics. It just comes down to a matter of syntax - basically, where you put the () to actually invoke this function and get your closure, and whether you use the new keyword.

    0 讨论(0)
  • 2021-02-01 17:52

    I don't see any substantial difference between the two. I would prefer the latter simply since it has much less punctuation clutter.

    On the other hand the "module pattern" approach seems to be the most common and is becoming a well known pattern (due to the rise in JQuery). It might be better to stick with this recognised pattern not because it has any more technical merit than the other approach but just because it will likely be more recognizable (despite the heavy punctuation).

    0 讨论(0)
提交回复
热议问题