2011-06-27

JavaScript: new無しで基本型のコンストラクタを呼んだ時の挙動

Closure Compilernew無しのArray()を使うのを見て興味を持ったので調べた。適当にまとめるとこうなる。

型名挙動
Object
String
Boolean
Number
引数をその型に変換
Function
Array
RegExp
Error
newがあるときと同じ
Datenew Date().toString()と同様
(引数は無視される)

Dateだけ挙動が不思議。

以下ECMA Scriptの仕様書より抜粋。

15.2.1 The Object Constructor Called as a Function
When Object is called as a function rather than as a constructor, it performs a type conversion.

15.2.1.1 Object ( [ value ] )
When the Object function is called with no arguments or with one argument value, the following steps are
taken:
1. If value is null, undefined or not supplied, create and return a new Object object exactly as if the standard
built-in Object constructor had been called with the same arguments (15.2.2.1).
2. Return ToObject(value).

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

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.5.1 The String Constructor Called as a Function
When String is called as a function rather than as a constructor, it performs a type conversion.
15.5.1.1 String ( [ value ] )
Returns a String value (not a String object) computed by ToString(value). If value is not supplied, the empty
String "" is returned.

15.6.1 The Boolean Constructor Called as a Function
When Boolean is called as a function rather than as a constructor, it performs a type conversion.
15.6.1.1 Boolean (value)
Returns a Boolean value (not a Boolean object) computed by ToBoolean(value).

15.7.1 The Number Constructor Called as a Function
When Number is called as a function rather than as a constructor, it performs a type conversion.
15.7.1.1 Number ( [ value ] )
Returns a Number value (not a Number object) computed by ToNumber(value) if value was supplied, else
returns +0.

15.10.3.1 RegExp(pattern, flags)
If pattern is an object R whose [[Class]] internal property is "RegExp" and flags is undefined, then return R
unchanged. Otherwise call the standard built-in RegExp constructor (15.10.4.1) as if by the expression new
RegExp(pattern, flags) and return the object constructed by that constructor.

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