Is JavaScript's “new” keyword considered harmful?

前端 未结 12 2071
情书的邮戳
情书的邮戳 2020-11-21 23:18

In another question, a user pointed out that the new keyword was dangerous to use and proposed a solution to object creation that did not use new.

12条回答
  •  后悔当初
    2020-11-21 23:33

    Case 1: new isn't required and should be avoided

    var str = new String('asd');  // type: object
    var str = String('asd');      // type: string
    
    var num = new Number(12);     // type: object
    var num = Number(12);         // type: number
    

    Case 2: new is required, otherwise you'll get an error

    new Date().getFullYear();     // correct, returns the current year, i.e. 2010
    Date().getFullYear();         // invalid, returns an error
    

提交回复
热议问题