When does *not* using new work on built-ins?
使用内置的JavaScript对象和构造函数,我注意到有点奇怪的东西。
有时,通过调用不带
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规范中的任何位置定义了非新构造函数内置函数的行为? 请注意,此行为实际上很有用; 我可以通过调用
是的,ECMA-262(我使用5.1版作为参考)确实定义了在使用或不使用
对于
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 callArray(…) is equivalent to the object creation expressionnew Array(…) with the same arguments.
15.4.2数组构造函数:
When
Array is called as part of anew expression, it is a constructor: it initialises the newly created object.
对于
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 callDate(…) is not equivalent to the object creation expressionnew 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规范。
对于
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.
对于
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.
因此,无论是否使用
例如,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.