3

I'm just working through Codeacademy, and they show you have to write both. But they don't explain why you'd need both.

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
  • http://stackoverflow.com/questions/4859800/should-i-be-using-object-literals-or-constructor-functions, http://stackoverflow.com/questions/14226299/javascript-object-constructor-vs-object-literal – nicosantangelo Jun 01 '13 at 21:59

2 Answers2

6

A constructor gives an object a sense of identity. It's essentially a blueprint for how to create it which can be re-used. It is very similar to and often confused with a class in classical OOP.

If you frequently have a bunch of "car" objects and there are methods or properties which often go with all cars, you can create a Car constructor to help encapsulate it.

function Car(numPassengers) {
  this.numPassengers = numPassengers;
}

Car.prototype = {
    accelerate: function () {
      // blah
    },
    brake: function () {
      // blah
    }
};

var jetta = new Car(4);
var bmwZ4 = new Car(2);

An object literal is a way to pass a just-in-time object whose structure and creation does not need to be re-used. To compare to classical OOP, similar to a Map in Java (except that javascript object literals can still have methods). A common use case is a function which takes a bunch of possible parameters, but each one is optional.

function someActionThatTakesOptionalParams(options) {
  if (options.doAlert) {
    alert(options.doAlert);
  }
  if (options.someOtherProperty) {
    // do some work
  }
}

someActionThatTakesOptionalParams({
  doAlert: 'this will show up in an alert box',
  someOtherProperty: 5,
  hello: 'world'
});

It's also a convenient way to just model data that gets passed to something else with no methods attached. For example, you have an API that takes JSON:

$.ajax({
  url: 'someApiEndpoint',
  method: 'get',
  params: {
    x: 5,
    y: 10
  }
});
Brandon
  • 9,822
  • 3
  • 27
  • 37
0

Not a stupid question. Actually, the Object constructor and especially the Array constructor can be tricky, since they take different parameters with different semantics which can make you incur subtle bugs.

The recommended way is to use the literals {} and []

MDN says:

> new Array(element0, element1, ..., elementN)
> new Array(arrayLength)

The first sentence constructs an Array and pushes every argument into it. The second sentence constructs an Array of length = arrayLength. What happens if you try to construct-push an Array with a single element that happens to be an integer? Gotcha!

LexLythius
  • 1,904
  • 1
  • 12
  • 20