xxxxxxxxxx
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Class Inheritance</h2>
<p>Use the "extends" keyword to inherit all methods from another class.</p>
<p>Use the "super" method to call the parent's constructor function.</p>
<p id="demo"></p>
<script>
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
</script>
</body>
</html>
xxxxxxxxxx
class Parent {
constructor(name){
this.name = name;
}
}
class Child extends Parent {
constructor(name, school){
super(name); // Super must be called before setting child options
this.school = school;
}
}
xxxxxxxxxx
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"