Loading...
New webinar: "The Remote Job Search: My Microverse Journey" with graduate Paul Rail
Watch Now

In programming, one of the most used data structures is OBJECT. This is also called a dictionary in other programming languages. In most cases, in Object-Oriented Programming (OOP), we need to create custom objects to suit what we intend to use them for.

While there are many approaches to creating objects in JavaScript, we will focus on the OOP pattern in this article. Before we proceed, let’s take a look at what an object is and how it can be created.

{% code-block language="js" %}
class Person {}
const john = new Person();
john.name = ‘John’;
john.gender = ‘Male’
{% code-block-end %}

That is all we need to create a custom object. Quite simple and easy. What if we need to create another ‘person’ object though?

{% code-block language="js" %}
const jane = new Person();
jane.name = ‘Jane’;
jane.gender = ‘Female’
{% code-block-end %}

John and Jane got married and gave birth to Mike, now we need to create another person object for Mike.

         Photo by Wes Hicks at Unsplash

You can see we’re repeating a lot of things, which doesn’t look good. Imagine creating a ‘person’ object for 200 people. That wouldn’t be fun!

This is where constructors come in.

Basic Concepts to Know About JavaScript Constructors

There are many concepts you should know for working with JavaScript Constructors.

One essential thing to know is that you need to capitalize the name of constructors to distinguish them from regular functions.

Another is that constructors call with the "new" operator.

In OOP, constructors allow you to create many objects of the same type. Each time you use the new keyword, the constructor is called and a new object is created. The newly created object shares characteristics with other objects that are created from the same constructor. For example, instance methods.  

Now, you might be thinking about how this helps us with our issue above. Well, with constructors, we can also specify distinct properties of our objects which will not be shared with other objects created from the same constructor.

Going back to the example above, we will redefine our class as below.

{% code-block language="js" %}
class Human {
   constructor(name, gender) {
   this.name = name;
   this.gender =  gender;
 }
}
{% code-block-end %}

While the keyword ‘this’ is arguably the most complicated part of JavaScript - and out of the scope of this article - keep in mind that ‘this’ represents an instance object created from the constructor. Now, we can instantiate a new object and pass in the parameters specified in the constructor.

{% code-block language="js" %}
const paul = new Person(‘Paul’, ‘Male’);
{% code-block-end %}

We just created a new person with a name and gender in one line of code!

Constructor Keyword

In JavaScript constructors, inheritance is useful for code reusability. We have the extends keyword and super() method.

The extends keyword is used to create a subclass that is a child class of a parent class. 

The super()method is actually the parent class constructor.

{% code-block language="js" %}
class Employee extends Human{
            constructor(name, gender, salary) {
    super(name, gender);
    this.salary = salary;
  }
work(salary) {
  this.salary = salary
}

{% code-block-end %}


There is no point in having a child class if it doesn't inherit properties from the parent class. So, passing the arguments of the parent constructor into the super() method will also initialize the parent class properties in our child class, thereby inheriting it.

How to Determine the Type of Object using Instanceof 

The way to check if an object is an instance of its constructors is through instanceof. instanceof allows you to compare an object to constructors returning either true or false. 

For example,

{% code-block language="js" %}
class Food() {
   constructor(name,restaurant) {
    this.name = name;
           this.restaurant =restaurant;
}
}
let hobby = new Food("Yam and Egg", “Basma Foods”);
hobby instanceof Food    //true

{% code-block-end %}

instanceof will also return ‘false’ if the object created is not from the constructors. For example:

{% code-block language="js" %}
let chew = {
name: "Swallow",
price: $200
 
}; 
chew instanceof Food      //false
 
{% code-block-end %}

Using Prototypes in Javascript

Have you ever thought about what happens in a car manufacturing company?

Do they design an engine from scratch for every single vehicle? If they do, that would be stressful.

If they don't, then that means you don't have to create an object from scratch every time. Object in JavaScript just got easier.

An engine is designed based on a prototype that serves as a model. The engine replicates in other vehicles with small modifications for various brands but all based on one prototype.

So, why do we want to redefine or revamp an object that has been created before?

For example, we have a Camry object and a Corolla object. The two-vehicle uses a V6  engine.

{% code-block language="js" %}
let camry= {
 engine: “v6”,
};
let corolla= {
 engine: “v6”,
};

{% code-block-end %}

Looking at these codes, we would see what is called duplication of code. The way to prevent this is to create a constructor in which both objects can inherit the properties from it.

Prototypes are the medium by which JavaScript objects inherit properties and methods from one another.

The method is applied to the prototype, so it is only stored in the memory once, but every instance of the object has access to it. 

Let’s take a look at this Human object:

{% code-block language="js" %}
 class Human(){
      constructor(name, gender) {
   this.name = name;
   this.gender =  gender;
 }   
}
function face(){ 
return  this.name  + ”is a” + this.gender 
 } 
Human.prototype.face = face;
 const person1 = new Human("Stephen' "Green"); 
console.log(person1.face()); // ""

{% code-block-end %}

Prototypes make it possible to create an object which inherits each of the methods and properties of the Person object. 

For example:

{% code-block language="js" %}
class Human(){
      constructor(name, gender) {
   this.name = name;
   this.gender =  gender;
 }  
}
      function Student(name, gender) {
        this.name = name;
    this.gender =  gender;
        this.age = 30;
      }
      Student.prototype = new Human();
      Student.prototype.identity = function () {
        console.log('Books');
      };
      const person2 = new Student('Emmanuela', 'Stone');
      console.log(person2.face()); // ""
      person2.identity(); // Outputs "Books"

{% code-block-end %}

Our Student object still inherits from the Human object because of Student.prototype = new Human();. 

The Student object has inherited the face method from the Human object. 

{% code-block language="js" %}
   const person1 = new Person('Stephen', 'Green');
     person1.identity(); // Error

{% code-block-end %}

The above example will result in an error when you call it because the identity method is custom to the Student Object. 

Conclusion

Above we showcased JavaScript constructors and their functions in order to decode JavaScript languages. We also covered the use of the instanceof method to check if an object is an instance of constructors. Your new knowledge of JavaScript constructors should help you feel confident using them and more efficiently understand JavaScript as a language.

Happy coding!


Subscribe to our Newsletter

Get Our Insights in Your Inbox

Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.