[removed] The Good Parts - How to not use `new` at all

前端 未结 9 1944
迷失自我
迷失自我 2020-12-07 09:15

Crockford\'s book, JavaScript: The Good Parts, says (on page 114) that constructor functions should always be given names with an initial capital letter (i

9条回答
  •  没有蜡笔的小新
    2020-12-07 09:51

    You can avoid "new" by returning an anonymous object and using a closure in your constructor. This also help you hide private data.

    Consider:

    function SomeCounter(start) {
    
        var counter = start;
    
        return {
            getCounter : function() {
                return counter;
            },
    
            increaseCounter : function() {
                counter++;
            }
    
        };
    }
    

    Now to use this, all you need to do is

    var myCounter = SomeCounter(5);
    myCounter.increaseCounter();
    console.log(myCounter.getCounter()); //should log 6
    

    The beauty of this is that you do not need to remember to use "new", but if you do it won't hurt you.

    var myCounter = new SomeCounter(5); //still works
    

提交回复
热议问题