在Javascript中,在构造函数的实例周围包上括号意味着什么

What does having brackets wrapped around the instance of constructor mean in Javascript?

本文关键字:什么 意味着 周围包 实例 Javascript 构造函数      更新时间:2023-09-26

我发现了这段我不太理解的代码。

var Vehicle = function Vehicle(color) {
  this.constructor;       // function Vehicle()
  this.color = color;
}
(new Vehicle("tan")).color;   // "tan"

为什么有(new Vehicle("tan")).color

为什么额外的()

我在这个博客中找到了代码http://pivotallabs.com/javascript-constructors-prototypes-and-the-new-keyword/

它什么都不做。new运算符优先于函数调用(()部分),因此它与键入new Vehicle("tan").color相同。然而,它确实使代码更可读,我建议使用它

为了自己演示这里发生了什么,试着摆弄一下语法,看看会发生什么:

new Date().getTime()   //1397073088727
(new Date()).getTime() //1397073088727
new (Date()).getTime() //error
new (Date)().getTime() //1397073088727
Date().getTime()       //error
new (Date().getTime()) //error