Object Constructor Functions

Open the project folder

In our starter files, open the index.html page from this lessons folder:

07.Objects-In-More-Depth > 02.Object-constructor-functions

Creating a constructor function

We now know of 2 ways to create JavaScript objects:

// 1. object literal
let user = {};

// 2. using new Object():
let user = new Object();

Both work fine, but they are limited to only creating a single object. It would be helpful if we could have an object template so we can create multiple objects. Each sharing the same properties and methods. You can think of this as a factory for creating similar objects.

factory image

We can do this with a constructor function:

// considered good practice to begin constructor function names with a capital letter:
function User() {}

Making use of a simple user example, we can use this function as a template to create multiple user objects. And this can take in the first, last and occupation:

function User(first, last, occupation) {}

We will come back to this in just a moment. Previously, we created a new Object() like this:

function User(first, last, occupation) {}
new Object()

But now we have our custom constructor function, we say new User():

function User(first, last, occupation) {}
new User('Chris', 'Dixon', 'Dev');

Using our constructor to create multiple objects

This also takes in the three values we want to pass to the function. We can duplicate this as many times as we want:

function User(first, last, occupation) {}
new User('Chris', 'Dixon', 'Dev');
new User('Homer', 'Simpson', 'Safety Inspector');

Then store these users into variables so we can use them later:

const chris = new User('Chris', 'Dixon', 'Dev');
const homer = new User('Homer', 'Simpson', 'Safety Inspector');

If we now log one of these variables, we will just have an empty User object in the console:

console.log(homer); // User {}

This is to be expected because our constructor function is empty. We are taking in the values into these parameters:

function User(first, last, occupation) {}

Setting object properties

But we have not set these to be our objects properties yet. To do this, we need to set something to be equal to these values:

function User(first, last, occupation) {
  = first
  = last
  = occupation
}

But what do we do to turn these into our object’s properties?

The this keyword

To set a property we need to make use of the this keyword. We have already looked at this in an earlier lesson, A Function Or a Method. In here, you may remember we have this object:

let checkRecipes = {
  currentRecipes: 137,
  maxRecipes: 1000,
  checkAllergies: function (recipe, ingredient) {
    const hasIngredient = recipe.includes(ingredient);
    return hasIngredient;
  },
  numberOfIngredients: function (recipe) {
    return recipe.length;
  },
  recipesLeft: function () {
    return this.maxRecipes - this.currentRecipes;
  },
};

This object has properties such as currentRecipes. And methods such as recipesLeft.

Remember, a method is just a function which is located on an object. Inside of the recipesLeft method, we used the this keyword to access other properties on the main object. We accessed maxRecipes and currentRecipes.

The this keyword can be a complex thing to understand, but in these circumstances, it will point to the object which owns it. We can now add our properties in the same way, using the this keyword followed by the property name:

function User(first, last, occupation) {
  this.firstName = first;
  this.lastName = last;
  this.occupation = occupation;
}

Give this a try, and both objects should have the same property names, but make use of the values we pass to the function:

console.log(chris);
console.log(homer);

Adding to our objects

If we need to add extra properties and methods, we have some options. We can add them directly to one of our objects like this:

// ...
const chris = new User("Chris", "Dixon", "Dev");
const homer = new User("Homer", "Simpson", "Safety Inspector");

// 1. add a property
homer.lives = "springfield";

// 2. add a method
homer.fullName = function () {
  return homer.firstName + " " + homer.lastName;
};
console.log(homer.lives);
console.log(homer.fullName());

This works completely fine, but these are only added to our homer object.

If we try to access the fullName method on our chris object:

console.log(chris.fullName());

We will see an error:

Uncaught TypeError: chris.fullName is not a function

This is only to be used if we want to change one specific object. If we want to make these apply to all created objects, we need to place these on the constructor function:

function User(first, last, occupation, lives) {
  this.firstName = first;
  this.lastName = last;
  this.occupation = occupation;
  this.lives = lives;
  this.fullName = function () {
    return this.firstName + ' ' + this.lastName;
  };
}

And we need to also pass the lives value when we create the new User objects:

const chris = new User('Chris', 'Dixon', 'Dev', 'UK');
const homer = new User('Homer', 'Simpson', 'Safety Inspector', 'Springfield');

We do not need to pass in anything for the method as it uses the firstName and lastName already inside the function.