Classes and constructors in javascript

We will see below topics here.
  • creating constructor using old JS syntax
  • Class keyword
  • constructor keyword
  • Static methods in class
  • getters and setters for object
  • Inheritance

Create a class using old syntax


//creating objects using literals

let Car =  function(make,price,features){
    this.make=make;
    this.price = price;
    this.features = features;
}

let car4 = new Car("Honda", 20000, ['abs','alarm']);
console.log("car 4 " + JSON.stringify(car4));
//output - car 4 {"make":"Honda","price":20000,"features":["abs","alarm"]}

using new Class syntax (ES6)


//new class syntax
class CarClass{

    constructor(make,price,features){
        this.make = make;
        this.price = price;
        this.features = features;
    }

    //static method
    static process() {
        console.log("inside static method");
    }

    //getters and setters
    get getMake(){
        return this.make;
    }
    set setMake(make){
        this.make = make;
    }
}

let car2 = new CarClass("Honda", 20000, ['abs','alarm']);
console.log("car 2 " + JSON.stringify(car2));
CarClass.process();
car2.make = "Audi";
console.log("car 2 " + JSON.stringify(car2));

//inheritance

class CompactCar extends  CarClass{
    constructor(make, price, features) {
        super(make, price, features);
    }
    display() {
        console.log("Inside display" + JSON.stringify(this));
    }
}

let compactCar = new CompactCar("Honda", 20000, ['abs','alarm']);
compactCar.display();
console.log("compactCar " + JSON.stringify(compactCar));

Complex problems, Simple Solutions