JavaScript class extends is creating a class that is a child of another(parent) class. Where the child class inherits all the methods from the parent class.
class ChildClass extends ParentClass {
/* ... */
}
JavaScript class extends
A simple example code creates a class that is a child of another class.
<!DOCTYPE html>
<html>
<body>
<script>
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} stands still.`);
}
}
// Extends class
class Rabbit extends Animal {
hide() {
console.log(`${this.name} hides!`);
}
}
let rabbit = new Rabbit("Tiger");
rabbit.run(50);
rabbit.hide();
</script>
</body>
</html>
Output:
Using extends with built-in class
class DateFormatter extends Date {
getFormattedDate() {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${this.getDate()}-${months[this.getMonth()]}-${this.getFullYear()}`;
}
}
console.log(new DateFormatter('August 19, 1975 23:15:30').getFormattedDate());
// expected output: "19-Aug-1975"
Do comment if you have any doubts or suggestions on this JS class topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version