The previous lesson in this module looked at how this is bound and how to stop fighting it, and this one builds on that by looking at inheritance. JavaScript inheritance is two keywords that do two separate jobs. extends wires a new class into an existing prototype chain, so that instances of the child can find the methods of the parent. super is how the child talks back to the parent, where super(...) runs the constructor of the parent and super.method() runs a parent method against the current object. Get those two ideas straight and the rest of the topic is detail.
The previous lesson in this module covered "this Binding and How to Stop Fighting It", and this lesson is the last one in the JavaScript Classes and Prototypes module.
What does extends actually do?
It creates the links. The prototype object of the child gets the prototype object of the parent as its own prototype, and the constructor of the child gets the constructor of the parent as its own prototype. That gives you two separate chains, which are a chain of objects for the instances and a chain of constructors for the static members.
class Notification {
constructor(recipient) {
this.recipient = recipient;
this.sent = false;
}
send() {
this.sent = true;
return "notification sent to " + this.recipient;
}
}
class EmailNotification extends Notification {
constructor(recipient, subject) {
super(recipient);
this.subject = subject;
}
}
const mail = new EmailNotification("[email protected]", "Invoice");
console.log(mail.recipient);
console.log(mail.subject);
console.log(mail.sent);
console.log(mail instanceof EmailNotification);
console.log(mail instanceof Notification);
The recipient and the subject both land on the object, and sent starts off false. Both of the instanceof checks print true, and that is the practical payoff of the whole idea. An email notification really is a notification, so code that accepts "any notification" can accept one without caring which kind it is.
Here is the chain underneath it, with nothing hidden.
class Notification {}
class EmailNotification extends Notification {}
const mail = new EmailNotification();
console.log(Object.getPrototypeOf(mail) === EmailNotification.prototype);
console.log(Object.getPrototypeOf(EmailNotification.prototype) === Notification.prototype);
console.log(Object.getPrototypeOf(EmailNotification) === Notification);
console.log(mail instanceof Notification);
console.log(mail instanceof EmailNotification);
Read the instance chain first, which is the mail object, then EmailNotification.prototype, then Notification.prototype, and then Object.prototype. A method that only exists on Notification.prototype is still reachable from an email notification, because the lookup walks upwards. The third line shows the other chain, where the constructor of the child has the constructor of the parent as its prototype, and that is what makes the static members inheritable. The last two lines print true, and instanceof is quietly doing the same walk as the prototype lookup, because it checks whether Notification.prototype appears anywhere in the chain of the object.
When must you call super, and where?
Inside the constructor of a derived class, you must call super(...) exactly once, and you must do it before you touch this in any way. The reason is that this does not exist yet at the start of a derived constructor. The object is not created until the parent constructor has run, because the parent constructor is the code that decides what the object looks like.
class Notification {
constructor(recipient) {
this.recipient = recipient;
}
}
class BrokenNotification extends Notification {
constructor(recipient) {
try {
this.subject = "oops";
super(recipient);
} catch (err) {
console.log("first failure: " + err.constructor.name + ": " + err.message);
}
}
}
try {
new BrokenNotification("[email protected]");
} catch (err) {
console.log("second failure: " + err.constructor.name + ": " + err.message);
}
Both lines print the same ReferenceError, with the message Must call super constructor in derived class before accessing 'this' or returning from derived constructor. The first failure is the assignment to this.subject, which happens before super has run. The second failure is the constructor trying to finish without ever having called super at all. Two different mistakes with one message.
The practical rule is short: make super(...) the first statement in the constructor and then assign your own fields. If you find yourself wanting to compute something before super, compute it into a local variable first and pass that in, because the arguments of a constructor are evaluated before the call and so they are allowed to use anything you like.
How do you call the parent's version of a method?
You use super.method(). It runs the implementation from the parent, but with this still pointing at the current object, so the parent method sees the data of the child.
class Notification {
constructor(recipient) {
this.recipient = recipient;
this.sent = false;
}
describe() {
return "to " + this.recipient;
}
send() {
this.sent = true;
return "notification sent " + this.describe();
}
}
class EmailNotification extends Notification {
constructor(recipient, subject) {
super(recipient);
this.subject = subject;
}
describe() {
return "to " + this.recipient + " about " + this.subject;
}
send() {
const result = super.send();
return result + " via email";
}
}
const mail = new EmailNotification("[email protected]", "Invoice");
console.log(mail.send());
console.log(mail.sent);
console.log(mail.describe());
The first line prints notification sent to [email protected] about Invoice via email. Look closely at why the subject appears in the middle, because super.send() runs the method of the parent, and that method calls this.describe(), which resolves to the version of the child and not the version of the parent. The method of the parent and the method of the child are working together on the same object, and the child wins every override. mail.sent is true, because the send of the parent set it, and the last line prints to [email protected] about Invoice.
Notice that super.send() is called as a method, so this inside it is the mail object. That is what makes overriding safe, because if the parent method assigns to this.sent, it updates the object of the child rather than some separate parent instance.
Why does inheritance make a mixed list of types easier?
Because you can write the loop once. Each subclass overrides the same method name, and the caller never needs a type check at all.
class Notification {
constructor(recipient) {
this.recipient = recipient;
}
send() {
return "base notification for " + this.recipient;
}
}
class EmailNotification extends Notification {
send() {
return "email to " + this.recipient;
}
}
class SmsNotification extends Notification {
send() {
return "sms to " + this.recipient;
}
}
const outbox = [
new Notification("[email protected]"),
new EmailNotification("[email protected]"),
new SmsNotification("+911234567890"),
];
for (const item of outbox) {
console.log(item.send());
}
The loop prints base notification for [email protected], then email to [email protected], and then sms to +911234567890. Each object answers the same call with its own behaviour, and the loop does not care which kind it is. That is polymorphism, and it is the real reason to reach for inheritance in the first place.
If you find yourself writing if (item instanceof EmailNotification) branches inside the loop, that is a sign that the hierarchy is not modelling the problem. Often composition, where each object holds a list of the things that it can do, is a better fit.
Do static members get inherited as well?
Yes, they do. The chain of constructors is the chain of the static members, so a child class sees the static methods of the parent unless it defines its own.
class Notification {
static channel() {
return "generic";
}
static priority() {
return "normal";
}
}
class EmailNotification extends Notification {
static channel() {
return super.channel() + "/email";
}
}
console.log(EmailNotification.channel());
console.log(EmailNotification.priority());
console.log(Object.getPrototypeOf(EmailNotification) === Notification);
EmailNotification.channel() prints generic/email, because the override calls the version of the parent through super. EmailNotification.priority() prints normal, because priority was never overridden and is found further up the constructor chain. The last line prints true, and that is the mechanism behind both of them, because the constructor of the child has the constructor of the parent as its prototype, and the static methods live on the constructors.
What are the traps worth knowing before you inherit anything?
supermust run beforethisin a derived constructor, and it may only be run once. Calling it a second time throws aReferenceErrorthat readsSuper constructor may only be called once.superonly exists inside the methods and constructors of a class, so using it in a plain function is a syntax error rather than a runtime one.- An arrow function inside a method has no
superof its own, sosuperinside an arrow refers to the class of the method that surrounds it. That is handy, but it means you cannot usesuperin a callback that is meant to run outside the class. - A parent constructor that returns an object changes what
thismeans in the child, becausethisis then that returned object. That is rare, but it is surprising when it happens. - Inheritance couples the child to the internals of the parent, so if a field of the parent is renamed, every child that touched it breaks. Composition keeps that coupling on one side only.
Before you move on
extendslinks the prototype of the child to the prototype of the parent, and the constructor of the child to the constructor of the parent.super(...)runs the constructor of the parent, and it has to come first and it may only be called once.super.method()runs a parent method withthisstill pointing at the object of the child, which is what makes overriding compose instead of replace.- Overrides are resolved at the moment of the call, so the method of the parent sees the version of the child for any method that it calls.
- Static members are inherited through the chain of the constructors, in the same way that prototype methods are inherited through the chain of the prototypes.
- Use inheritance for genuine is-a relationships, and hold a reference instead when the relationship is a has-a one.
Try it yourself: build class Shape with a constructor that takes a name and a method describe() that returns "a " + this.name. Then build class Circle extends Shape whose constructor calls super(name), stores a radius, and overrides describe() so that it calls super.describe() and appends " with radius " + this.radius. Create a circle and check that describe() prints both parts, that circle instanceof Shape is true, and that Object.getPrototypeOf(Circle.prototype) === Shape.prototype is true as well. Finally, write a deliberate bug by putting this.radius = radius above the super(name) call and run it. Read the ReferenceError carefully, then fix the order and run it again.