extendclass
A simple prototype-based subclassing function.
Installation
$ npm install extendclass
Usage
This function extends a class using the prototype inheritance chain, under the paradigm of single inheritance. It does not allow more than one subclassing to take place at the same time. If you want multiple chains, you must make multiple calls. Call this function immediately after the child class's constructor.
Short Example
var extend = { thislegs = n} Animalprototype { console} { Animal} // THIS IS IMPORTANT. DO THIS. Dogprototype { console}
Long Example with Comments
var extend = { thislegs = n}Animalprototype { console} var buzz = 6console // 6buzz // 'nom nom nom'
buzz.legs
logs 6 because that's specified by the constructor. buzz.eat()
logs
'nom nom nom'
because that function is defined on Animal.prototype
, and
buzz.__proto__ === Animal.prototype
.
{ Animal // calls the super constructor specifying 4 legs}Dogprototype { console} var rex = console // 4,rex // 'woof woof'rex // undefined!!!
rex.legs
logs 4 because that's given by Dog
constructor calling the Animal
constructor. rex.bark()
logs 'woof woof'
because that's inherited from
rex.__proto__
. But rex.eat()
is undefined.
Why? Because rex.__proto__ === Dog.prototype
, which does not have or inherit an eat
function.
We need to insert the following line after the Dog
constructor, but before any
modifications to Dog.prototype
(such as adding a bark
function).
This does two (2) things:
-
Dog.prototype = Object.create(Animal.prototype)
We need to let
Dog.prototype
have aneat
function, and all other functions onAnimal.prototype
. But we cannot setDog.prototype = Animal.prototype
because this is only a pointer. If we modifyDog.prototype
we risk modifyingAnimal.prototype
as well. Thus we needDog.prototype
to inherit fromAnimal.prototype
. One way to do this would beDog.prototype.__proto__ = Animal.prototype
This would be all fine and good, but setting the
.__proto__
for an object is generally a bad idea, so we useObject.create()
as a safe shortcut instead. This creates a new object whose.__proto__
isAnimal.prototype
and assigns that object toDog.prototype
. -
Dog.prototype.constructor = Dog
Since
Dog.prototype
inherits fromAnimal.prototype
, its constructor will be that ofAnimal
. That is, when you invokenew Dog()
, it will use theAnimal
function. Thus we "reset" theDog
constructor back to theDog
function.
Now the right way:
var axel = console // 4axel // 'woof woof'axel // 'nom nom nom'
Now axel.eat()
logs 'nom nom nom'
because that function is inherited from
axel.__proto__.__proto__
, which === Animal.prototype
.
See the MDN tutorial for more info. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain