在使用“new”创建对象时,我们可以省略括号吗?运营商? [英] Can we omit parentheses when creating an object using the "new" operator?

查看:191
本文介绍了在使用“new”创建对象时,我们可以省略括号吗?运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过以这种方式创建的对象:

I have seen objects being created this way:

const obj = new Foo;

但我认为在创建对象时括号不是可选的:

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

const obj = new Foo();

创建对象的前一种方式是否有效并在ECMAScript标准中定义?前一种创建对象的方式和后一种方法之间是否存在差异?一个优先于另一个吗?

Is the former way of creating objects valid and defined in the ECMAScript standard? Are there any differences between the former way of creating objects and the later? Is one preferred over the other?

推荐答案

引用 David Flanagan 1


作为一个特殊的例如,对于 new 运算符,JavaScript通过允许在函数调用中没有参数时省略括号来简化语法。以下是使用 new 运算符的一些示例:

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.

此外, JSLint 可能会伤害您的感受省略括号。它报告 Missing'()'调用构造函数,并且似乎没有工具允许括号省略的选项。

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权威指南:第4版(第75页)

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

这篇关于在使用“new”创建对象时,我们可以省略括号吗?运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆