To create a class inheritance, use the extends keyword. A
class created with class inheritance inherits all the methods from another class. This allows
you to build hierarchical relationships and reuse code efficiently.
Inheritance allows a "child" class to inherit logic from a "parent" class.
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand); // Calls the parent constructor
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
let myCar = new Model("Ford", "Mustang");
console.log(myCar.show());
The super() method refers to the parent class. By calling the
super() method in the constructor, we call the parent's constructor method and
gets access to the parent's properties and methods.
Classes also allow you to use getters and setters. It can be smart to use getters and setters for your properties, especially if you want to do something special with the value before returning them, or before setting them.
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname.toUpperCase();
}
set carname(x) {
this._carname = x;
}
}
myCar.carname.
extends to create a subclass (child)super() method is mandatory in the child constructor
get) and Setters
(set) provide controlled access to data_carname) to indicate "private" or internal
properties