2

In JavaScript one can make an object by using the incorporated constructor of Object:

var person = new Object();
person.firstName = 'John';
person.lastName = 'Doe';

Almost all people seem to prefer the way of object-creation as a literal:

var person2 = {
  firstName: 'Peter',
  lastName: 'Smith'
}

Now I'm wondering: Why is the constructor-way ignored completely?

But especially: Are there cases in which one should prefer one way over the other?

I mean the constructor-way must be in there for some reason ...

Mat
  • 202,337
  • 40
  • 393
  • 406
mewi
  • 539
  • 1
  • 4
  • 11
  • 2
    Possible duplicate of [What is the difference between \`new Object()\` and object literal notation?](http://stackoverflow.com/questions/4597926/what-is-the-difference-between-new-object-and-object-literal-notation) – Sebastian Simon Jun 29 '16 at 06:15
  • if you don't need inheritance, stick with literals. – dandavis Jun 29 '16 at 07:13

1 Answers1

5

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();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875