Please enable JavaScript to use CodeHS

Advanced Objects (Pt 1) in JavaScript

In this tutorial, you will learn about object constructors and why they are essential for programs that create many objects.

By Ryan Hart

This is part 1 in the Advanced Objects tutorials. Be sure to check out part 2, object prototypes and inheritance, when you are done here!


In the Basic Objects tutorial, we discussed how to create individual object literals and set up their properties and methods. While those techniques are useful when declaring one-off objects, if you want to create multiple instances of the same object (multiple cars or balls, for example), it’s more effective to develop what is called an object constructor.

The Object Constructor

At its core, the object constructor is like a factory that produces specific objects when called. It looks like a mix between an object literal and a function, and it defines all of the properties and methods that will be included in an object when one is created. Here is a basic structure of a person object constructor:

function Person( // parameter list // ) {
    // Property definition list
    // Method definition list
}
Plain text

By convention, constructor function names always start with a capital letter.


Adding Properties

Let’s get more specific with this example and add a few properties and methods to the Person constructor. Since we want to be able to call this constructor to produce a unique person object, we’ll use parameters to set the initial values of the properties.

function Person(firstName, ageYears, hairColor, healthPoints, hobbiesList) {
    // Property list
    this.name = firstName;
    this.age = ageYears;
    this.hair = hairColor;
    this.health = healthPoints;
    this.hobbies = hobbiesList;
}
JavaScript

A few things to notice here:

  • While an object literal uses the format key: "value" to create properties, constructors are just functions and have to use dot notation (or bracket notation) to do the same thing.

  • Since the properties are inside of the constructor, the keyword this refers to the object that is being created. In other words, this.name = ... will create a name property for an object when it is made.

  • Unlike object literals that must be just a list key-value pairs inside { }, a constructor is a function, so it can include things like comments, variables, control structures, etc.


Adding Methods

Let’s now add a couple of methods to the Person constructor, greet() and heal().

function Person(firstName, ageYears, hairColor, healthPoints, hobbiesList) {
    // Property list
    this.name = firstName;
    this.age = ageYears;
    this.hair = hairColor;
    this.health = healthPoints;
    this.hobbies = hobbiesList;

    // Method list
    this.greet = function() {
        console.log("Hi! My name is " + this.name + ".");
    };

    this.heal = function(amount) {
        this.health += amount;
        if (this.health > 100) {
            this.health = 100;
        }
    };
}
JavaScript

The only difference between the properties and methods is that the method value is a function. Otherwise the setup code in the constructor is identical.

Creating Objects

Once you have an object constructor, aka the factory, you can call it to produce objects! Every object that is made using the constructor is an individual, standalone object, with the same list of properties and methods. They share the same blueprint, but now act independently of one another.

To create an object, all you have to do is place the keyword new in front of the function call. Let’s create our first person, “Adriana”.

let adriana = new Person("Adriana", 15, "brown", 100, ["climbing", "cooking"]);
JavaScript

It’s as simple as that! The line above produces the same thing as the object literal:

let adriana = {
    name: "Adriana",
    age: 15,
    hair: "brown",
    health: 100,
    hobbies: ["climbing", "cooking"],
    greet: function() {
        console.log("Hi! My name is " + this.name + ".");
    },
    heal: function(amount) {
        this.health += amount;
        if (this.health > 100) {
            this.health = 100;
        }
    }
}
JavaScript

The powerful thing about constructors, however, is that it is now super easy to create multiple people based off the same template.

let georgia = new Person("Georgia", 22, "black", 98, ["soccer", "singing"]);
let chidi = new Person("Chidi", 36, "black", 90, ["philosophy", "eating"]);
let elliot = new Person("Elliot", 10, "blond", 95, ["piano", "reading"]);

georgia.greet();    // prints "Hi! My name is Georgia."
chidi.greet();        // prints "Hi! My name is Chidi."
JavaScript

Take a look at the Person constructor in action in the editor. Try creating your own person and having them greet you. Then add them to the people array to have their health printed with the group!

A Graphics Example

In the example below, there is a Organism constructor that creates organism objects (line 37). On line 26, these organisms are created with a WebImage graphic object as their graphic property. Can you imagine how terribly cumbersome this program would be if you did not include the constructor, and had to individually create 30 different organisms and set their properties!?

Hopefully you’re convinced on how valuable objects and object constructors can be in your programs! Be sure to take a look at part 2 of the Advanced Objects tutorials, object prototypes and inheritance, which provides even more motivation to build those constructors!