When does *not* using new work on built
This question already has an answer here:
The behaviour of a native method depends on the EcmaScript specification.
For Date
the spec says :
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.
and for Array
the spec says
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.
So how it works with or without the new
keyword is completely dependant on what method you're using, and what the spec says should happen when called without the new keyword.
For instance, the Math object is different again
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.
Yes, ECMA-262 (I am using 5.1 Edition for reference) does define how should object constructors behave when called with or without the new
keyword.
For Array
:
15.4.1 The Array Constructor Called as a Function:
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 The Array Constructor:
When Array
is called as part of a new
expression, it is a constructor: it initialises the newly created object.
For Date
:
15.9.2 The Date Constructor Called as a Function:
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 The Date Constructor:
When Date
is called as part of a new expression, it is a constructor: it initialises the newly created object.
上一篇: “新”对JS方法有什么影响?
下一篇: 什么时候不*使用新的工作