JavaScript Constructor Function

In this section, we will learn what the Constructor Function is and how to use it in JavaScript.

What is Constructor Function in JavaScript? (AKA JavaScript Object Constructor)

In the object literal section, we’ve explained one way of creating objects in the JavaScript.

But if we want to create a couple of dozens of objects and all with the same body; using the technique of object literal (writing down each object one by one) becomes tedious and cumbersome.

It would be much easier if we could use a shorter and quicker method to create objects when they all have the same body!

This is where the second way of creating objects which is constructor-function comes in.

Constructor functions are used to create objects.

At its core, there’s no specialty about constructor functions and typical functions. We use the term constructor to point the fact that the target function is designed to create objects from. But there’s absolutely no limit on using a constructor function for other purposes as well.

Object Creation in JavaScript: Constructor Function Syntax

The function below is an example of a function constructor:

function Person(firstName, lastName){
        this.firstName = firstName; 
        this.lastName = lastName;
        this.printInfo = function(){
          console.log(this.firstName, this.lastName);
        }
}

The name of this function is `Person`, it takes two arguments and put them in the `firstName` and the `lastName` parameters. These two parameters are then assigned to the `firstName` and the `lastName` properties of the target object that the `this` keyword binds to.

Note: if you don’t know about `this` keyword, please refer to the `this` section.

So, obviously, this is a typical function.

Now how we use such a function to be used as object constructor?

This is where the `new` keyword comes in.

`new` Keyword JavaScript

By adding the `new` keyword in front of a function when it is being called, the function becomes a constructor and will create a new object.

Example: using new keyword and constructor function to create new object in JavaScript

function Person(firstName, lastName){
  this.firstName = firstName; 
  this.lastName = lastName;
  this.printInfo = function(){
    console.log(this.firstName, this.lastName);
  }
}
const obj = new Person("John","Doe");
obj.printInfo();

Output:

John Doe

Take a look at this statement:

const obj = new Person("John","Doe");

Here, by adding the `new` keyword in front of the `Person()` function, behind the scene the execution engine will:

  1. Create an empty object. Empty means the newly created object does not have any property in it yet. So at this stage, we have something like this in the memory: `{ }`
  2. It will link this empty object to another object. (We will return to this topic in the prototype section). For now, just remember that a link from this empty object to another object will be created.
  3. In the body of the `Person` function, the `this` keyword binds to this newly created empty object.

So if we call this newly created object as `NCO` then the body of the function becomes like this:

function Person(firstName, lastName){
        NCO.firstName = firstName; 
        NCO.lastName = lastName;
        NCO.printInfo = function(){
          console.log(this.firstName, this.lastName);
        }
      }

What will happen is that the `firstName`, `lastName` and the `printInfo` identifiers become the property of this newly created object.

So at this stage, this new object has a body like this:

{
        firstName: "John",
        lastName: "Doe",
        printInfo: function(){
          console.log(this.firstName, this.lastName);
        }
}

4- At the end, this new object will be stored in the memory and its memory address will return.

So because here we’ve assigned the result of calling the `Person()` function via the `new` keyword into the `obj` identifier, the memory address of the newly created object is stored in this identifier.

Now this identifier represents the newly created object.

Example: constructor function in JavaScript

function Person(firstName, lastName){
  this.firstName = firstName; 
  this.lastName = lastName;
  this.printInfo = function(){
    console.log(this.firstName, this.lastName);
  }
}
const prs1 = new Person("John","Doe");
const prs2 = new Person("Omid","Dehghan");
prs1.printInfo();
prs2.printInfo();

Output:

John Doe

Omid Dehghan

As you can see here, we’ve created 2 objects from the `Person` constructor.

Note: Even though we used one constructor to create objects from, those objects are independent from each other. This means if we changed the property of one object or add a new one, the other object won’t take effect!

`instanceof` in JavaScript

After creating multiple objects from multiple different Constructor functions, sometimes you might want to know if an object was created from a specific Constructor function or not.

Basically, you might want to know the type of the object you’ve created.

This is where we can use the `instanceof` operator.

This operator takes two values:

  • The first value that we put on the left side of this operator is the object we want to know its type.
  • The second value which will be put on the right side of this operator is the type we want to check and see if that is the type of our object.

The operator will then return a boolean value indicating whether the value is of declared type. The value true means the type is the one we’ve set on the right side of this operator and the value of false means otherwise.

Note: the instanceof operator is explained in greater details in later section.

Example: using instanceof in JavaScript

function Person(name, lastName){
  this.name = name;
  this.lastName = lastName; 
}
const person = new Person("Omid","Dehghan");
console.log(person instanceof Person);

Output:

true

As you can see, the `person` object is of type `Person`.

JavaScript Built-in Constructor Functions:

JavaScript has a set of built-in constructors as well.

For example, the `Number` constructor is a built in function that can be used to create objects to represent a number but in form of an object.

An object that is created from `Number` constructor has multiple useful methods and properties that can be applied on numbers.

Other than `Number` constructor, which we will explain it in a greater detail in later chapters, there are other constructors already created in the JavaScript.

Here’s a short list of these constructors:

  • Object(): This constructor can be used to create objects from.
  • String(): This constructor can be used to create string objects from.
  • Boolean(): Via this constructor, we can create Boolean objects.
  • Array(): This constructor can be used to create array objects from.
  • RegExp(): Via this constructor, we can create regular expression objects.
  • Date(): This constructor is useful when we want to create a Date object.
  • Function(): This constructor is used to create Function objects.

Again, each of these constructors and many others are covered in this tutorial and you’ll see their use cases in later sections.

Alright, there’s another important topic which is called `prototype`. We highly recommend to check the prototype section as well to learn this important and related topic.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies