Javascript
/
Classes
- 1 Fundamentals 11
-
Hello World
-
Code structure
-
Use strict
-
Variables
-
Data types
-
Type conversions
-
Maths
-
Comparitions
-
Conditional
-
Loops
-
Functions
- 2 Testing 2
-
Mocha
-
Nested describe
- 3 Objects 4
-
Basics
-
Reference
-
Methods
-
Constructor
- 4 Types 5
-
Primitives
-
Numbers
-
Strings
-
Arrays
-
Json
- 5 Classes 3
-
Constructor
-
Binding
-
Inheritance
/
Inheritance
➟
➟
Last update: 27-01-2022
Extend
Inheritance is a way for one class to extend another class.
/**
* Extend another class
*/
class Animal
{
constructor(name) {
this.speed = 0;
this.name = name;
}
run(speed) {
this.speed = speed;
console.log(`${this.name} runs with 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("My Rabbit");
rabbit.run(100);
// My Rabbit runs with speed 100
rabbit.stop();
// My Rabbit stops
rabbit.run(50);
// My Rabbit runs with speed 50
rabbit.hide();
// My Rabbit stops
// My Rabbit hides!
Super
Constructors in inheriting classes must call super(), and do it 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 Animal
{
constructor(name) {
this.speed = 0;
this.name = name;
}
}
class Rabbit extends Animal
{
constructor(name) {
super(name); // Look Here
this.name = name.toUpperCase();
}
}
let rabbit = new Rabbit("My Rabbit");
console.log(rabbit.name); // MY RABBIT
➥ Questions github Classes