class Dog extends Animal is shorthand. Underneath, it builds two constructor functions and links their prototype objects, so a dog finds Animal's methods when Dog does not have them. Older code, some libraries and many interview rounds still write that link by hand, and knowing each step explains what extends and super actually do.
Write inherit, Animal and Dog in animals.jswithout the class keyword: constructor functions, prototype objects and the functions Object gives you.
Animal: own property name. Methods speak() returns "<name> makes a sound."; eat(food) returns "<name> eats <food>.". A static function Animal.create(...args) builds a new instance of the constructor it is called on.
Dog: an Animal with the own properties name and breed. speak() returns Animal's sentence followed by " Woof!"; describe() returns "<name> is a <breed>.".
inherit(Child, Parent): links the two constructors and returns Child.
An animal's only own key is name; speak and eat live once on Animal.prototype.
A dog's own keys are name and breed, in that order, and each dog keeps its own values.
A dog uses Animal.prototype.eat itself (not a copy): Object.getPrototypeOf(Dog.prototype) is Animal.prototype, and a dog is an instance of Dog, Animal and Object.
Dog.prototype.speak overrides Animal's and builds on it: "Rex makes a sound. Woof!".
Plain animals get none of Dog's methods, and still say "… makes a sound.".
Dog.prototype.constructor is Dog and is not enumerable; Animal.prototype.constructor is still Animal.
A change made to Animal.prototype later reaches dogs that already exist.
Dog inherits Animal's static functions: Object.getPrototypeOf(Dog) is Animal, and Dog.create("Rex", "beagle") builds a Dog.
Animal(…) and Dog(…) called without new throw a TypeError.
inherit(Child, Parent) works for any two constructor functions: it does all of the linking in requirements 4, 7 and 9, returns Child, and never calls Parent. Methods added to Child.prototype afterwards stay off Parent.prototype.
constrex=newDog("Rex", "beagle");rex.speak(); // "Rex makes a sound. Woof!"rex.eat("bones"); // "Rex eats bones."rex.describe(); // "Rex is a beagle."Object.keys(rex); // ["name", "breed"]
JAVASCRIPT
newAnimal("Tom").speak(); // "Tom makes a sound."newAnimal("Tom").describe; // undefinedDog.create("Fido", "pug") instanceofDog; // trueDog("Rex"); // TypeError
JAVASCRIPT
functionShape(sides) { this.sides = sides; }functionSquare() { Shape.call(this, 4); }inherit(Square, Shape); // returns Square, and Shape did not runnewSquare() instanceofShape; // true
Plain JavaScript in a browser page; the tests call the globals inherit, Animal and Dog from animals.js.
The class keyword is not allowed (the tests check that Animal and Dog are not classes). Object.create, Object.setPrototypeOf, Object.defineProperty and call are fine.