关于javascript:什么时候*不*在内置插件上使用新工作?

When does *not* using new work on built-ins?

本问题已经有最佳答案,请猛点这里访问。

使用内置的JavaScript对象和构造函数,我注意到有点奇怪的东西。

有时,通过调用不带new的构造函数可以获得新对象。 例如:

1
2
3
4
> new Array(1,2,3,4)
[1, 2, 3, 4]
> Array(1,2,3,4)
[1, 2, 3, 4]

但有时这不起作用:

1
2
3
4
> Date()
"Thu Jun 05 2014 00:28:10 GMT-0600 (CST)"
> new Date()
Date 2014-06-05T06:28:10.876Z

是否在ECMAScript规范中的任何位置定义了非新构造函数内置函数的行为? 请注意,此行为实际上很有用; 我可以通过调用Array.apply(arr)来创建一个非稀疏的数组副本,但是如果它是跨平台的话,我只会感到很自在。


是的,ECMA-262(我使用5.1版作为参考)确实定义了在使用或不使用new关键字调用时对象构造函数应该如何表现。

对于Array

15.4.1作为函数调用的数组构造函数:

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

15.4.2数组构造函数:

When Array is called as part of a new expression, it is a constructor: it initialises the newly created object.

对于Date

15.9.2日期构造函数称为函数:

When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC).
The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments.

15。9。3日期构造函数:

When Date is called as part of a new expression, it is a constructor: it initialises the newly created object.


本机方法的行为取决于EcmaScript规范。

对于Date,规范说:

When Date is called as a function rather than as a constructor, it
returns a String representing the current time (UTC).

NOTE : The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments.

对于Array规范说

When Array is called as a function rather than as a constructor, it
creates and initialises a new Array object.

Thus the function call
Array(…) is equivalent to the object creation expression new Array(…)
with the same arguments.

因此,无论是否使用new关键字,它的工作原理完全取决于您使用的方法,以及在没有new关键字的情况下调用时应该发生的规范。

例如,Math对象再次不同

The Math object does not have a [[Construct]] internal property; it is
not possible to use the Math object as a constructor with the new
operator.