So, I'm looking at the ES5 specification at the definition of what new Object
and Object
do. To my surprise:
new Object
describes a whole algorithm of how the object constructor works - treating what happens with different kinds of values. Basically callsToObject
on non objects - identity on objects and builds on null and undefined.Object
has a special first step for null and undefined where it builds an object and then callsToObject
on primitives and identity on objects.
After reading the description a few times - they seem identical. However, clearly from the spec they do something different. For example in Array
- calling new Array
is specified as the function call Array(…)
is equivalent to the object creation expression new Array(…)
with the same arguments.`
So - what is the difference between new Object
and Object
? Why were they specified differently?
For ease - here's a link to the spec.
Object(window)
will never clonewindow
butnew Object(window)
might. All current -- potentially all known -- implementations just return the same reference, although the spec allows for implementation-defined behavior.The steps for 15.2.1.1 say:
The definition of
ToObject
(9.9) lists a few types that will be caught by step 1 (in table 14), but forObject
has a very simple definition:It explicitly states that the input argument will be returned as-is, so they should be equal references (
===
).The definition for
new Object
(15.2.2.1) has a similar chain of type-checks in step 1, but the step for objects (1.a) is:That is, for any host object
foo
, the callObject(foo)
must=== foo
butnew Object(foo)
may=== foo
.Host objects are defined in 4.3.8 to be
This answer lists a few host objects to include
window
,history
, etc. Running those throughnew Object(foo)
should (but doesn't have to) return a different object.In any case but passing a host object,
new Object(foo)
seems to be a more complicated chain that defers toToObject
in much the same way asObject(foo)
.Unfortunately, 15.2.2.1.1.a.ii states that the "result is returned in an implementation-dependent manner" and has no specifics as to the "actions [that] are taken" and it appears that Chrome will return the same object (equal references) for all of the listed "host objects."
Using this script to check:
doesn't find any objects where
Object
andnew Object
behave differently. @Xotic750 seems to be right that it can be implementation-dependent, but nobody is using it.