javascript - 我们可以在使用 "new"运算符创建对象时省略括号吗?

标签 javascript new-operator

我见过这样创建对象:

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 the new 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/

相关文章:

Javascript 算力实数/非理性数库

c++ - 何时使用 Malloc 而不是 New

module - 无法在 OpenERP 6 中安装新模块

r - S4 类 : arguments passed to new() don't go into their slots

javascript - 双重警报窗口

javascript - Promise.defer() 浏览器支持

javascript - 尝试从js中的另一个文件调用变量时出错

javascript - jquery匹配多个数据组(仅当它们都为真时)

c++ - 如何删除在 C++ 中的本地函数中创建的对象?

c# - WPF XAML TextBlock 将内容发送到新行