Review: Using JavaScript Objects

Objects are an essential data type of JavaScript, and learning how to use them is necessary to develop applications. We will start with a quick review of objects from the first course. Try the examples in this article to review creating and manipulating objects, accessing objects using dot [.] notation and bracket notation, and setting and getting object members. You can use the JavaScript Console on your browser DevTools to complete the examples.

Introducing constructors

Using object literals is fine when you only need to create one object, but they're seriously inadequate if you have to create more than one, as in the previous section. We have to write out the same code for every object we create, and if we want to change some properties of the object - like adding a height property - then we have to remember to update every object.

We want a way to define the "shape" of an object - the set of methods and the properties it can have - and then create as many objects as we like, just updating the values for different properties.

The first version of this is just a function:

function createPerson(name) {
  const obj = {};
  obj.name = name;
  obj.introduceSelf = function () {
    console.log(`Hi! I'm ${this.name}.`);
  };
  return obj;
}

This function creates and returns a new object each time we call it. The object will have two members:

  • a property name
  • a method introduceSelf().

Note that createPerson() takes a parameter name to set the value of the name property, but the value of the introduceSelf() method will be the same for all objects created using this function. This is a very common pattern for creating objects.

Now we can create as many objects as we like, reusing the definition:

const salva = createPerson("Salva");
salva.name;
salva.introduceSelf();
// "Hi! I'm Salva."

const frankie = createPerson("Frankie");
frankie.name;
frankie.introduceSelf();
// "Hi! I'm Frankie."

This works fine but is a bit long-winded: we must create an empty object, initialize it, and return it. A better way is to use a constructor. A constructor is just a function called using the new keyword. When you call a constructor, it will:

  • create a new object
  • bind this to the new object so that you can refer to this in your constructor code
  • run the code in the constructor
  • return the new object.

Constructors, by convention, start with a capital letter and are named for the type of object they create. So we could rewrite our example like this:

function Person(name) {
  this.name = name;
  this.introduceSelf = function () {
    console.log(`Hi! I'm ${this.name}.`);
  };
}

To call Person() as a constructor, we use new:

const salva = new Person("Salva");
salva.name;
salva.introduceSelf();
// "Hi! I'm Salva."

const frankie = new Person("Frankie");
frankie.name;
frankie.introduceSelf();
// "Hi! I'm Frankie."