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

前端 未结 9 1938
迷失自我
迷失自我 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:40

    I think his advice of not using new at all is conceptual (academic) and not to be taken literally. The Date class is a perfect exception to the rule because how else can you get a current (or arbitrary) date object using standard ECMAScript?

    However, regarding not using new with your own custom objects you can use a few strategies. One is to use factory-like methods instead of constructors which could take as an argument an object instance to "bless" into your new type, or use a new object literal by default. Consider the following:

    var newCar = function(o) {
      o = o || {};
      // Add methods and properties to "o"...
      return o;
    }
    

提交回复
热议问题