Sub class with ES6
ES6 introduces subclass syntax which is just an easy way to extends a class to another.
Subclass
When you create class you may have a class who have his own properties, methods but can also have the same than another class instead of rewrite all this methods or properties you can inherit this class with an other one.
class Person = {
constructor(name, secondName, age) {
this.name = name;
this.familyName = secondName;
this.age = age;
}
calculateAge() {
return new Date().getFullYear() - this.age;
}
eat() {
return `${this.name} is eating`;
}
static hey() {
return `Hello world`;
}
};
class Athlete extends Person = {
constructor(name, secondName, age, olympicGames, medals) {
super(name, secondName, age);
this.olympicGame = olympicGames;
this.medal = medals;
}
action() {
return `${ super.eat() } something`;
}
winMedals() {
return this.medal++;
}
}
- To inherit a class to another you have to use the
extendskeyword and the name of the parent class herePerson. - Like we declare a class we use the
constructorfunction in order to define properties when we will create an object based on this class, so the parameters will be our new properties. - Inside the
constructorfunction we have a new functionsuperthis function is used to access and call functions on an object parent she's necessary when you use inheritance with class and must be used directly inside theconstructorfunction if you want be able tu use thethiskeyword inside this class. - In parameters you have to call all the properties and functions of the parent class, after that you can start to use the
thiskeyword to define your own new properties. - As you may seen we created a new function inside the
Athleteclass and we use thesuperkeyword to call theeatfunction of thePersonclass, you can also access to the functions parent with thesuperkeywords which is this time not a function but an object.