Extend
Inheritance is a way for one class to extend another class.
/**
* Inheritance, one class extends 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`); // backsticks to embed vars
}
}
class Rabbit extends Animal {
hide() {
super.stop(); // Look Here
console.log(`${this.name} hides!`);
}
}
let rabbit = new Rabbit("A");
rabbit.run(100); // A runs, speed 100
rabbit.stop(); // A stops
rabbit.run(50); // A runs, speed 50
rabbit.hide(); // A stops
// A hides!
Super
Constructors in inheriting classes must call super() before using this.
/**
* If a class extends another class and has no constructor,
* then a default constructor is generated
* constructor(...args) { super(...args); }
*
* We get an error when trying to add a custom constructor
* without calling super() first
*/
class A {
constructor(name) {
this.speed = 0;
this.name = name;
}
}
class X extends A {
constructor(name) {
super(name); // Look Here
this.name = name.toUpperCase();
}
}
class Y extends A {
constructor(name) { // no super()
this.name = name.toUpperCase();
}
}
let a = new X("aaa");
console.log(a.name); // AAA
try {
let b = new Y("bbb"); // doesnt' work
console.log(b.name);
} catch (err) {
console.log(err.name); // ReferenceError
console.log(err.message); // Must call super in constructor
}
Last update: 357 days ago