En plus d’avoir ajouté les classes en JavaScript, ES6 continue avec l’héritage. Plus besoin de l’héritage prototypal. 👍
Avant, il fallait appeler la méthode call pour hériter du constructeur. Par exemple, pour développer une classe Voiture et Moto, héritant de la classe Vehicule, on écrivait quelque chose comme ça :
function Vehicle (color, drivingWheel) {
this.color = color;
this.drivingWheel = drivingWheel;
this.isEngineStart = false;
}
Vehicle.prototype.start = function start() {
this.isEngineStart = true;
}
Vehicle.prototype.stop = function stop() {
this.isEngineStart = false;
};
// Une voiture est un véhicule.
function Car(color, drivingWheel, seatings) {
Vehicle.call(this, color, drivingWheel);
this.seatings = seatings;
}
Vehicle.prototype = Object.create(Vehicle.prototype);
// Une moto est un véhicule également.
function Motorbike (color, drivingWheel, unleash) {
Vehicle.call(this, color, drivingWheel);
this.unleash = unleash;
}
Motorbike.prototype = Object.create(Vehicle.prototype);
Maintenant on peut utiliser le mot clé extends en JavaScript (non, non ce n’est pas une blague), et le mot-clé super, pour rattacher le tout à la « superclasse », ou « classe-mère » si vous préférez.
class Vehicle {
constructor(color, drivingWheel, isEngineStart = false) {
this.color = color;
this.drivingWheel = drivingWheel;
this.isEngineStart = isEngineStart;
}
start() {
this.isEngineStart = true;
}
stop() {
this.isEngineStart = false;
}
}
class Car extends Vehicle {
constructor(color, drivingWheel, isEngineStart = false, seatings) {
super(color, drivingWheel, isEngineStart);
this.seatings = seatings;
}
}
class Moto extends Vehicle {
constructor(color, drivingWheel, isEngineStart = false, unleash) {
super(color, drivingWheel, isEngineStart);
this.unleash = unleash;
}
}
Le code est quand même plus clair et concis avec cette nouvelle syntaxe.