JavaScript Prototype Based Inheritance

JavaScript is a classless and object-oriented language. It is different from class-based programming languages. In class-based languages; the structure of objects are specified in classes and the structure of all the instances of the objects are the same. But in javascript you don't need to specify the structure of the object. You define the elements of the objects dynamically. For defining the elements (properties and functions) of the all instances of an object you use prototypes

In JavaScript language a prototype is an object from which other objects inherit properties and functions. Prototypes allows you to implement inheritance in JavaScript. You can set the prototype property of an object by another object;

function Animal() { } // animal constructor
Animal.prototype.age = 5;

function Bird() { } // bird constructor
var animal = new Animal();
Bird.prototype = animal; // inheritance
Bird.prototype.canFly = true;

var bird = new Bird();
alert(bird.age); // 5

alert(animal.canFly); // TRUE
alert(bird.canFly); // TRUE

var anotherAnimal = new Animal();
alert(anotherAnimal.canFly); // undefined

In the example above we declared Animal and Bird constructors then inherited Bird from Animal by setting the prototype property of Bird with a new Animal instance. And then added a canFly property to the prototype of Bird. When we set the canFly property of the both animal and bird instances are true. Because the prototype property of Bird is equal to animal instance. But when we created an new instance of Animal, the canFly property is undefined because we didn't define canFly property of Animal.

We can encapsulate the prototype inheritance in the constructor of Animal;

function Animal() { }
Animal.prototype.age = 5;

function Bird(animal){
  function F() {}
  F.prototype = animal;  
  F.prototype.canFly = true;
  
  return new F();
}

var bird = new Bird(new Animal());
alert(bird.age); // 5
alert(bird.canFly); // TRUE

 A more encapsulated implementation is this one;

var Animal = (function(){
  function F() { }
  
  F.prototype.age = 5;
  
  return F;
})();

var Bird = (function(animal){
  function F() {}
  
  F.prototype = animal;
  F.prototype.canFly = true;
  
  return F;
})(new Animal());

var bird = new Bird();
alert(bird.age); // 5
alert(bird.canFly); // TRUE

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading