The super keyword connects a subclass to its superclass. Use it to initialize inherited properties through the superclass constructor or to reuse inherited methods while extending behavior. section 4.2.7 section 11.3.7
Use super in two common places:
- Call super(...) inside a subclass constructor to invoke the superclass constructor. In JavaScript, call it before using this; it is generally the constructor's first statement. section 4.2.7 section 11.3.7
- Call super.method(...) to reuse a superclass method, then combine its result with subclass-specific behavior. section 4.2.7
- When extends is used in TypeScript, invoking super ensures that inherited properties are initialized. section 11.3.7
Extending Product with TaxedProduct
class TaxedProduct extends Product {\n constructor(name, price, taxRate = 1.2) {\n super(name, price);\n this.taxRate = taxRate;\n }\n\n toString() {\n let result = super.toString();\n return `${result}, Tax: ${this.getPriceIncTax()}`;\n }\n}\n\nlet hat = new TaxedProduct("Hat", 100);\nconsole.log(hat.toString());\n// toString: Name: Hat, Price: 100, Tax: 120 section 4.2.7
TypeScript subclass initialization
class Person {\n constructor(public id: string, public name: string,\n public city: string) { }\n}\n\nclass Employee extends Person {\n constructor(public readonly id: string, public name: string,\n private dept: string, public city: string) {\n super(id, name, city);\n }\n} section 11.3.7
Listing 4.12 Extending a class in the index.js file in the primer folder
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
toString() {
return `toString: Name: ${this.name}, Price: ${this.price}`;
}
}
class TaxedProduct extends Product {
constructor(name, price, taxRate = 1.2) {
super(name, price);
this.taxRate = taxRate;
}
getPriceIncTax() {
return Number(this.price) * this.taxRate;
}
toString() {
let chainResult = super.toString();
return `${chainResult}, Tax: ${this.getPriceIncTax()}`;
}
}
let hat = new TaxedProduct("Hat", 100);
let boots = new TaxedProduct("Boots", 100, 1.3);
console.log(hat.toString());
console.log(boots.toString());
Inspect the complete JavaScript inheritance example, including Product, TaxedProduct, constructor initialization, method reuse, and output. section 4.2.7





