-1

What is the difference between using object literals and using constructor functions to create Objects (theoretically) and when to use each of them?

I don't mean how we use them. I mean how they both work behind the scenes and how their mechanisms differ!

Yousef Essam
  • 151
  • 1
  • 11
  • There are [many, many duplicates](https://stackoverflow.com/search?q=%5Bjavascript%5D+literal+vs+constructor). – RobG Aug 10 '17 at 22:47
  • I am not talking about how to use them. I am talking about what happens behind the scenes in js when I use both of them. I asked my question because I found that no other questions was meant for the point I am looking for... So my question isn't a duplicate! – Yousef Essam Aug 10 '17 at 22:57
  • The question has been edited if you care to answer. – Yousef Essam Aug 10 '17 at 23:03
  • ECMA-262 does not define implementation details (i.e. what happens "behind the scenes"), so asking about them is off topic here. You need to look at the code for specific implementations to see what happens. ECMA-262 describes the language in terms of behaviour. The (fairly minor) differences between initializers and constructors are well covered in the duplicates. The specification describes the [*processing of initializers*](http://ecma-international.org/ecma-262/8.0/#sec-object-initializer) in terms of the equivalent constructor process, so they are, theoretically, the same. ;-) – RobG Aug 10 '17 at 23:12

1 Answers1

1

Basically - before ES2015 - when creating an objects using object literals you couldn't add methods to the object.

As of ES2015 it is possible to add methods to object literals, which makes object literals and class declarations pretty close:

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return 'd ' + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

Another important thing is when you want to create instances of a class - you would want to create a class declaration and init objects based on that class declaration.

Dekel
  • 60,707
  • 10
  • 101
  • 129
  • Nice to point out the features introduced in ECMAScript 2015, most of the duplicates are a bit old. The additional features of Object initializers are also covered on [*MDN*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). Be wary of using `__proto__` though, it's an extension covered in an [*appendix to ECMA-262*](http://ecma-international.org/ecma-262/8.0/#sec-__proto__-property-names-in-object-initializers). – RobG Aug 10 '17 at 22:52