Can we omit parentheses when creating an object using the “new” operator?

前端 未结 6 2164
清酒与你
清酒与你 2020-11-22 00:41

I have seen objects being created this way:

const obj = new Foo;

But I thought that the parentheses are not optional when creating an objec

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 00:51

    Quoting David Flanagan1:

    As a special case, for the new operator only, JavaScript simplifies the grammar by allowing the parenthesis to be omitted if there are no arguments in the function call. Here are some examples using the new operator:

    o = new Object;  // Optional parenthesis omitted here
    d = new Date();  
    
    ...
    

    Personally, I always use the parenthesis, even when the constructor takes no arguments.

    In addition, JSLint may hurt your feelings if you omit the parenthesis. It reports Missing '()' invoking a constructor, and there doesn't seem to be an option for the tool to tolerate parenthesis omission.


    1 David Flanagan: JavaScript the Definitive Guide: 4th Edition (page 75)

提交回复
热议问题