Constructor Functions in JavaScript

Constructor Functions in JavaScript

Photo by C Dustin on Unsplash

We talked about functions and objects in previous articles. You may have already heard about Classes in programming and we will talk about them soon enough, but first we should understand how JavaScript constructs objects using functions.

Why Constructor Functions?

Since we already know a little about functions and objects in JavaScript, let's start with the WHY first. We use objects all the time in programming, not just JavaScript. If we use the long way of defining an object (or Object Literal Notation) ...

let userObject = {
    name: "Gillian",
    occupation: "CEO at Consulting Biz",
    age: 27
}

... then we have to do all that for each and every User object instance that we want to create and use in our program. For something small like this userObject it may not be that big a deal, but what happens when we have a much larger object with a dozen or so fields and just as many or more object methods? That would be a lot of extra coding for us as the developer if we had to do that for every User manually. And what if we had hundreds of thousands of Users we had to do that for? Exhausting just thinking about all that work.

So if we want to be able to create many similar Objects (Users in our case) then constructor functions help us do just that without having to repeat writing very similar or the same code over and over again. Are you familiar with DRY (Don't Repeat Yourself) principles in programming? If not we will cover them eventually, but let's continue with the topic at hand.

Constructor Function:

A constructor function is at the heart of it just a regular function, with some helpful additions. We differentiate a constructor function from a traditional function in two ways:

  • We define or name the function starting with a Capital letter.
  • We create a new instance object using the "new" keyword when calling our constructor function
// define the constructor function
function User( ) {
    // object code ...
}

// create a new user object instances
let user1 = new User( );
let user2 = new User( );
let user3 = new User( );

Constructor Function Parameters:

Creating static objects is not where the power of using constructor functions is the most useful. When we add parameters to the definition of our constructor function, this is where we can now create many similar but specific objects.

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

   // return this;
}

// create new user objects
let user1 = new User("Gillian", "Artsmith", "CEO at Consulting Biz", 27);
let user2 = new User("Kire", "Bigglesworth", "Bingo Champion", 35);
let user3 = new User("Rodger", "Rabbit", "Professional Cartoon", 24);

What does "new" do?

  • creates a new object in memory and assigns it to this
  • assigns the properties and methods to the this object
  • returns the instance of the object just created
function User(name, occupation, age) {
  // this = { };

  // add properties to "this"
  this.name = name;
  this.occupation = occupation;
  this.age = age;

  // return this; 
}

this refers to the instance of that object when the object is created.

Methods in a Constructor Function:

Since objects can have their own methods (or instance methods) we can easily create as many or as few methods needed for the object to interact with our application or other objects by adding them when we define the constructor function. Just like we did with the object properties we add the method(s) to the object instance or this. Unlike the implicit return at the end of our constructor function we must remember if we want the method to return anything, not just process some logic, then you have to include a return statement at the end of the method. Just like we would for any other method we define as part of an object.

function User(first, last) {
  // define object properties
  this.firstName = first;
  this.lastName = last;

   // define object methods
   this.getFullName = function( ) {
        return this.firstName + " " + this.lastName;     
   };

  // return this;     -->  Implicitly returns the current object instance
}

Accessing Object Properties and Methods:

The object instance properties and methods can be accessed the same way we access them if we created the object using object literal notation.

// Create two instance object
let obj1 = new User("Mickey", "Mouse");
let obj2 = new User("Donald", "Duck");

// Access properties
console.log(obj1.firstName);       //  output -> "Mickey"
console.log(obj2.firstName);      //   output -> "Donald"
console.log(obj1.getFullName( ));     // output -> "Mickey Mouse" 
console.log(obj2.getFullName( ));    // output -> "Donald Duck"

By thinking about how we want to structure our Objects, properties and methods, we can use our knowledge of Constructor Functions to help us build more useful and advanced applications with less code.

Hopefully this article on Constructor Functions in JavaScript was useful to you. Thanks for reading, until next time!