I mean the constructor-way must be in there for some reason ...
The Object
constructor was originally the only way to create an object. The object initializer syntax ({}
) was added in JavaScript 1.2, the updated JavaScript in Netscape Navigator 4.0 in 1997.
There are several reasons to prefer initializer syntax to the Object
constructor:
- It's shorter
- It's more expressive, particularly when using property initializers
- It can't be overridden/shadowed (whereas
Object
can be)1
In contrast, there is basically no reason to use Object
to create objects except indirectly, when using a variable that might point to the Object
function or might point to some other function, e.g.:
function constructAndInit(ctor, props) {
var obj = new ctor();
if (props) {
for (var key in props) {
obj[key] = props[key];
}
}
return obj;
}
// Maybe use use Object...
var foo = constructAndInit(Object);
// ...or maybe you use somnething else
var bar = constructAndInit(NiftyThingy);
We do, of course, routinely use the Object
function without calling it to create objects:
- Any time we want to get access to the root object prototype,
Object.prototype
- To use the functions that are properties of
Object
, like Object.create
, Object.defineProperty
, and such
1 "can't be overridden/shadowed (whereas Object
can be)" Here's an example of shadowing Object
:
function foo() {
var Object = {
foo: "bar"
};
// ...later...
var o = new Object(); // fails
}
foo();