Javascript
/
Classes
- 1 Fundamentals 11
-
Hello World S
-
Code structure S
-
Use strict S
-
Variables S
-
Data types S
-
Type conversions S
-
Maths S
-
Comparitions S
-
Conditional S
-
Loops S
-
Functions S
- 2 Testing 2
-
Mocha S
-
Nested describe S
- 3 Objects 4
-
Basics S
-
Reference S
-
Methods S
-
Constructor S
- 4 Types 5
-
Primitives S
-
Numbers S
-
Strings S
-
Arrays S
-
Json S
- 5 Classes 3
-
Constructor S
-
Binding S
-
Inheritance S
S
R
Q
Javascript Classes Inheritance
Inheritance, one class to extend another class Error when adding a constructor without super() class B extends A constructor(x) super(x); this.speed = x
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
}
➥ Questions