我见过这样创建对象:
const obj = new Foo;
但我认为创建对象时括号不是可选的:
const obj = new Foo();
前一种创建对象的方法是否有效并在 ECMAScript 标准中定义?前一种创建对象的方式和后一种方式有什么区别吗?一个比另一个更受欢迎吗?
最佳答案
引用 David Flanagan 1:
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 thenew
operator:o = new Object; // Optional parenthesis omitted here d = new Date(); ...
就个人而言,我总是使用括号,即使构造函数不带参数。
此外,JSLint如果省略括号,可能会伤害您的感受。它报告 Missing '()' invoking a constructor
,并且该工具似乎没有允许括号省略的选项。
1 大卫·弗拉纳根:JavaScript the Definitive Guide: 4th Edition (第 75 页)
关于javascript - 我们可以在使用 "new"运算符创建对象时省略括号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3034941/