Module pattern vs. instance of an anonymous constructor

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

提交回复
热议问题