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
Continue reading Javascript Constructors