Extending classes

We can also extend a previously existing class. To refer to the original constructor, use super(), and to refer to the parent's method, use super.method(); see the redefinition of .fullName() here:

// Source file: src/class_persons.js

class Developer extends Person {
constructor(first, last, language) {
super(first, last);
this.language = language;
}

fullName() {
// redefines the original method
return `${super.fullName()}, ${this.language} dev`;
}
}

let dd = new Developer("John", "Doe", "JS");
console.log(dd); // Developer {first: "John", last: "Doe", language: "JS"}
console.log(dd.initials()); // "JD"
console.log(dd.fullName()); // "John Doe, JS dev"

You are not limited to extending your own classes; you can also extend the JS ones, too:

// Source file: src/class_persons.js

class ExtDate extends Date {
fullDate() {
const months = [
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC"
];

return (
months[this.getMonth()] +
" " +
String(this.getDate()).padStart(2, "0") +
" " +
this.getFullYear()
);
}
}

console.log(new ExtDate().fullDate()); // "MAY 01 2018"

If you don't need a special constructor, you can omit it; the parent's constructor will be called by default.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.44.182