Javascript Constructors

To work in an object oriented way in javascript, you can create a function and define properties using the ‘this’ keyword.

Let’s take an example of a ‘Car’ class which has 3 propertiesmake‘, ‘model‘ and ‘year‘. It will look like this.

/// create a constructor function.
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

Now to create instances of this class or create objects of this class, you can use the new Keyword.

const car1 = new Car('Toyota', 'Corolla', 1980);

Now we can use the ‘.’ syntax on the object get values of properties.

console.log(car1.make); // 'Toyota'
console.log(car1.model); // 'Corolla'
console.log(car1.year); // 1980

Creating Methods

You can define methods on your objects like this.

/// create a constructor function.
function Car(make, model, year) {

  ...
  
  this.getDescription = function() {
    return `${this.make} ${this.model} - ${this.year}`;
  }

}

And we can use it like so:

const car1 = new Car('Honda', 'Civic', 2013);
console.log(car1.getDescription()); // Honda Civic - 2013

This is the gist. You can add parameters to the methods as well. And that’s how it goes.

Thankyou for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *