Javascript Inheritance – Prototype and Prototype Chain

I am a big fan of javascript and I love scripting. In this post I will be talking about one of the most important concepts in javascript. Inheritance, protoyping and prototype chain.

 

If you are familiar with oop (object-oriented programming) languages like C#, Java etc. then you know what inheritance is. Javascript inheritance is somewhat similar conceptually.
In classical oop inheritance you first create a “class” which is a blueprint for your objects. Then you can create objects from this class or you can extend your class to create new classes.
But javascript is a prototype-based language which has no “class” statement. This might be confusing to oop guys used to coding with C# etc. but defining a class in javascript is pretty easy. Javascript uses “functions” as classes.
Classes in Javascript:
Defining a class is just as easy as defining a function:
function human(){}
Objects in Javascript:
To create instances from classes (functions) you just use the “new” keyword as below:
var humanA = new human();
var humanB = new human();
In classical oop programming there are “constructor” methods for classes which are called at the moment of instantiation. The constructors are used to set the objects' properties or to call methods to prepare the objects for use. In javascript the “function” serves as the constructor of the objects. There is no need to explicitly define a constructor.
Properties in Javascript:
Properties are variables in a function (class). Every instance of a function (class) has them. To work with properties in a function you use “this” keyword. “This” refers to the current object (instance).
function human(gender){
   this.gender = gender; // here you define the “gender” property and assign the value of input parameter to it
}
var humanA = new human (“male”);
var humanB = new human (“female”);
Methods in Javascript:
Javascript methods are functions actually. To define a method, assign a function (anonymous function) to a named property of the function's (class in classical oop) “prototype” property. (More on “prototype” is coming…)
function human(gender){
   this.gender = gender;
}
human.prototype.walk = function(){
   console.log(“walking…”);
}
humanA = new human(“male”);
humanA.walk(); //prints “walking…” to the console
INHERITANCE:
Having talked about classes, objects, properties and methods in javascript we are now ready to proceed to the inheritance. Actually, you just saw a simple example.
Before we start note this: Javascript only supports single class inheritance! In javascript there can be only 1 parrent for a child class. No multiple inheritance.
To achieve the inheritance in javascript, you assign an instance of the parrent to the child and then specialize it as you like.
Example:
1) Create a parent class
function human(name){
   this.name=name;
} // you could also do it like this: var human = function(){}
2) Add methods to this parrent class
human.prototype.walk = function(){
   console.log(“walking…”);
}
human.prototype.talk = function(){
   console.log(“talking…”);
}
human.prototype.getName = function(){
   return this.name;
}
human.prototype.sayName = function(){
   console.log(“My name is: ” + this.getName());
}
3) Create a child class of type “human”
var humanA = new human(“serdar”);
alert(humanA.name); //alerts “serdar”
humanA.sayName(); //prints “serdar” to the console
As you can see above, child class inherits the methods of the parent. You can even add new methods/properties to the parent after creating the child. They will be automatically inherited by the child.
human.prototype.fly = function(){
   console.log(“flying…”);
}
humanA.fly(); //prints “flying…” to the console
 
Note: Instance properties can be set on each instance of the class, prototype properties are shared across all instances of the class.

humanA.myCustomProperty = “myCustomValue”;

Another Example:
Now let's create a class, extend that class and then create an instance of the extended class.
1) Base Class

function Animal(name) {

   this.name = name;
}
Animal.prototype.speak = function() {
   console.log(“My name is ” + this.name);
};

2) Extend the base class

function Dog(name)(){
   Animal.call(this, name);
}
Dog.prototype = new Animal();
 
3) Create an instance of the extended class
var dog = new Dog(“Tonny”);
dog.speak(); //prints “My name is Tonny” to the console.
 
See the sample code here: http://jsbin.com/OvIvizI/1/
 

Here we use Animal.call to inherit the Animal constructor so that we can have the “name” property on the Dog object and set its value when creating a new instance. We are also setting Dog's prototype to an instance of Animal so that Dog inherits all Animal prototype methods/properties.

 
Prototype and Prototype Chain:
 
I am sure how we add new methods/properties to a function (class) has cought your attention. Did you pay attention to the use of “prototype” keyword?
In javascript, objects have an internal property called “prototype”. You can use “prototype” for adding methods and properties to javascript objects.
In addition, this prototype property is actually a pointer to another object (Remember the line “Dog.prototype = new Animal();”?). If you look up for something(property or method) in a javascript object, javascript will look for it in object's prototype, and will keep looking for it in the prototype chain until it either finds the requested property or until it reaches the end of the chain. If you follow an object’s prototype chain, you will eventually reach the core “Object” prototype whose prototype is null, signalling the end of the chain. It is this prototype chain that allows us to implement inheritance.
For the Animal/Dog example above this is how the prototype chain works:

Dog –> Animal –> Object.prototype –> null

In javascript almost everything is an object. Functions, Arrays… All of them.

If you create an Array (myArray) the prototype chain would look like this:

myArray –> Array.prototype –> Object.prototype –> null

For a function f:

f –> Function.prototype –> Object.prototype –> null

Hope this helps someone.

Good luck,
Serdar.

Leave a Reply

Your email address will not be published. Required fields are marked *