Classes in JavaScript

We will see below topics here.

  1. creating constructor using old JS syntax
  2. Class keyword
  3. constructor keyword
  4. Static methods in class
  5. getters and setters for object
  6. 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));

Youtube | Facebook | Twitter | Website Home | Online Grocery Shopping Brisbane