Understanding JavaScript's Prototypal Inheritance
When I first started using JavaScript I was a bit confused about its inheritance model, coming from languages that use a classical inheritance model. For example, i'll use Java.
Class Animal{ ... }
Class Person{ ... }
We could say that a Boy is a Person and a Person is an Animal.
Class Person extends Animal{ ... }
Class Boy extends Person{ ... }
So with Java we extend other classes and implement interfaces. However, in JavaScript we use something called a Prototype Chain. Ever open up a jsfiddle or play around in the console? You might notice that when you console.log(someObject) you see at the bottom of the object definition something like.
__proto__: Object
You could open this up on any object and trace it up the prototype chain to the base object. To understand this better let's mimic what we did in the java example in JavaScript.
function Animal(){}
Animal.prototype = {
heartbeat: function(){ return 'bump bump, bump bump' }
};
Animal.prototype.constructor = Animal;
function Person(){
this.ears = 2
}
Person.prototype = new Animal();
Person.prototype.constructor = Person;
function Boy(){
this.toy = 'truck'
}
Boy.prototype = new Person();
Boy.prototype.constructor = Boy;
So we have a chain of functions that connect Boy, Person and Animal. Now if we were to create a new Boy.
var boy = new Boy();
Now that we have invoked a new boy, let's look at what it can do.
boy.heartbeat()
//"bump bump, bump bump"
boy has inherited the heartbeat function from Animal.
boy.ears
//2
boy has inherited the ears attribute from Person.
boy.toy
//truck
boy has its own toy attribute.
There are many ways to demonstrate this example. Open up a console and play around with it. Prototypal inheritance can be very powerful if used correctly. Did i get something wrong? Please tell me!