Extend Class in JavaScript

by shraddhapaghdar

JavaScript

class ParentClass {
  constructor(counter) {
    this.name = 'ParentClass';
    this.counter = counter;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
}

const parent = new ParentClass(300);
parent.sayName();
console.log('The counter of this parent class is ' + parent.counter);

class ChildClass extends ParentClass {
  constructor(counter) {
    super(counter);
    this.name = 'ChildClass';
  }

  get counter() {
    return this.counter;
  }
  set counter(value) {
    this.counter = value;
  }
}

const child = new ChildClass(5);

child.sayName();
console.log('The counter of this parent class is ' + child.counter);