Extend
Inheritance is a way for one class to extend another class.
class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
run(speed) {
this.speed = speed;
console.log(`${this.name} runs, speed ${this.speed}`);
}
stop() {
this.speed = 0;
console.log(`${this.name} stops`);
}
}
class Rabbit extends Animal {
hide() {
super.stop();
console.log(`${this.name} hides!`);
}
}
let rabbit = new Rabbit("A");
rabbit.run(100);
rabbit.stop();
rabbit.run(50);
rabbit.hide();
Super
Constructors in inheriting classes must call super() before using this.
class A {
constructor(name) {
this.speed = 0;
this.name = name;
}
}
class X extends A {
constructor(name) {
super(name);
this.name = name.toUpperCase();
}
}
class Y extends A {
constructor(name) {
this.name = name.toUpperCase();
}
}
let a = new X("aaa");
console.log(a.name);
try {
let b = new Y("bbb");
console.log(b.name);
} catch (err) {
console.log(err.name);
console.log(err.message);
}