Module pattern vs. instance of an anonymous constructor

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

提交回复
热议问题