Class Usage & Inheritance: 3 ways to inherit
There are 3 ways to extends a superclass:
1. For ES6, declare: class Subclass extends Superclass
example: class Mammal extends Animal { … }
2. For ES5, create an object based on the superclass prototype and set the subclass prototype’s constructor to the subclass’ FUNCTION:
Subclass.prototype = Object.create(Superclass.prototype);
Subclass.prototype.constructor = Subclass; // do NOT invoke function with ();
Superclass.call(this, <args>); // optional, but must call to get Superclass’ properties
example:
Mammal.prototype = Object.create(Animal.prototype); // inherit Superclass’ methods
Mammal.prototype.constructor = Mammal; // enables inheritance of Mammal
Animal.call(this); // inherit Superclass’ properties
3. For older Javascript (not ideal): Set class’ prototype to a new instance of parent class to connect the subclass’ prototype to the superclass’ __proto__ (aka [[Prototype]]):
Subclass.prototype = new Superclass();
Subclass.prototype.constructor = Subclass; // do NOT invoke function with ();
example: Mammal.prototype = new Animal(); // inherit superclass’ methods+properties
Mammal.prototype.constructor = Mammal; // this sets constructor = Mammal correctly since “new” sets constructor = Animal;
constructor usage in ES5:
If the constructor function explicitly returns a value, then the new instance created is not returned.
To call the parent’s constructor, use Function’s apply or call with “this” as the context:
function Mammal (name) { Animal.call(this, name); };
class & instance properties & methods in ES5:
1. Properties AND methods declared within the constructor are INSTANCE members, NOT class/ prototype members!
2. To create class methods, assign the function to the class’ prototype outside constructor: Animal.prototype.eat = function() { … };
3. To create class properties, assign the property to the ClassName: Animal.name
4. Instance properties & methods are created within the constructor:
this.myName = ‘name’;
5. To call the superclass method: Superclass.prototype.method.call(this): Animal.prototype.eat.call(this);