Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume

We just need to implement three concepts to build a prototype chain in Javascript.

First we create the base class:

function Animal(voice){
	this.voice = voice || grunt;
}
//We update the Animal prototype so that it has a function that can be used by all its derived classes

Animal.prototype.speak = function(){
	console.log(this.voice);
}

//Next we create our derived class, whose constructor calls the constructor of the base class
//in this case the Derived class is Cat and base class is Animal

function Cat(name, color){
	Animal.call(this, "Meeow");
	this.name = name;
	this.color = color;
}

//Note here that we call the base class constructor using the call method, since we need to
//ensure that we are using the current instance of the Cat class to be used as value of the 
//"this" keyword, when being used in the base class Animal.

//Next we ensure that the Cat's prototype refers to the object created from the Animal's prototype.
//Also note that we are using the Object.create method and not the "new" keyword
//inorder to create the Cat function's prototype object.
Cat.prototype = Object.create(Animal.prototype);
// We do this so that the constuctor of Animal is not called when we create the Cat's prototype.
//Also note that once we instantiate the cat's prototype to an instance of the Animal's protoype instance
// we automatically inherit the properties and function's of the Animal prototype
//thus extending the prototype chain.
//This means the Cat function now also has in it's armory the speak function automatically available 
//to it even though we did not explicitly define a speak function on the Cat function definition.
//Next
Cat.prototype.constructor = Cat;
//here we set the prototype's constructor to that of Cat... so that when we create 
//new instance of Cat, we ensure that the Object so created is an instance of the Cat function
//Next
var cat = new Cat("fluffy", "white");
//here we create and instnace of the Cat function and it automatically has the memebers, voice and speak
//as part of the "cat" object even though these properties and functions are 
//not specified as part of the Cat function.
//now  when we call cat.speak() it outputs "Meeow"
cat.speak() //Outputs - Meeow

Thus remember the Three important parts to creating a prototypical chain in javascript are the following three lines:

1 function Cat(name, color){ 2 Animal.call(this, "Meeow"); 3 } 4 Cat.prototype = Object.create(Animal.prototype); 5 Cat.prototype.constructor = Cat; 6

That is all that is there to creating a prototypical chain in Javascript

Posted on Monday, December 21, 2015 1:36 AM | Back to top


Comments on this post: Creating a prototype chain in Javascript

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Rohit Gupta | Powered by: GeeksWithBlogs.net