Class

class Car{
    constructor(name, wheels){
        this.name = name;
        this.wheels = wheels;
    }

    showDetail(){
        console.log(`${this.name} have ${this.wheels} wheels`);
    }
}

var c = new Car("BMW", 4);
c.showDetail(); // BMW have 4 wheels

Class Inheritance

class Car{
    constructor(name, wheels){
        this.name = name;
        this.wheels = wheels;
    }

    showDetail(){
        console.log(`${this.name} have ${this.wheels} wheels`);
    }
}

var c = new Car("BMW", 4);
c.showDetail(); // BMW have 4 wheels

class Maruti extends Car{

    constructor(){        
        super("Maruti", 4);
        this.cost = "20k";
        super.showDetail();
    }

    showDetail(){
        console.log(`${this.name} have ${this.wheels} wheels and it's cost is ${this.cost}`);
    }
}

var m = new Maruti();
m.showDetail(); // Maruti have 4 wheels and it's cost is 20k

Static Method

class Person {
  constructor(name) {
    this.name = name;
  }

  static myColor(){
        console.log('my color is Black');
    }

  getColor() { //class method
    console.log(`my name is ${this.name}`);
  }
}

var p = new Person('Hemant');
p.getColor();
Person.myColor();

Setter/Getter

used as properties not as methods

class Person {
  constructor(name) {
    this.name = name;
  }

  set name(name){
      this.username = name;
  }

  get name(){
      return this.username.toUpperCase();
  }
}

var p = new Person('Hemant');
p.name = 'papa you are great';
console.log(p.name); // PAPA YOU ARE GREAT

Last updated

Was this helpful?