JavaScript Prototypal Inheritance
by pwalczyszyn
HTML
<div id='output'></div>
JavaScript
var print = function(text) {
$('#output').append('<p>' + text + '</p>');
};
// ******* DEFINING PARENT TYPE *******
var Parent = function(a) {
// Setting type instance level properties
this.a = a;
print('Parent type constructor called');
};
// Defining funA function that will be inherited by descendant types
Parent.prototype.funA = function() {
print('Parent.funA called');
};
// ******* DEFINING CHILD TYPE *******
var Child = function(a, b) {
// Calling parent type constructor function
Parent.call(this, a);
// Setting type instance level properties
this.b = b;
print('Child type constructor called');
};
// This will give Child access to Prent functions
// Object.create() function requires ECMAScript5 compatible browser,
// if this is not supported just a new instance of Prent type could be used instead
Child.prototype = Object.create(Parent.prototype);
// Defining funB that will be only available for Child type instances
Child.prototype.funB = function() {
print('Child.funB called');
};
// ******* DEFINING GRANDCHILD TYPE *******
var GrandChild = function(a, b, c) {
// Calling parent type constructor function
Child.call(this, a, b);
// Setting type instance level properties
this.c = c;
print('GrandChild type constructor called');
};
// This will give GrandChild access to Parent and Child functions through a prototypes chain
GrandChild.prototype = Object.create(Child.prototype);
// Overriding ParentType.funA function
GrandChild.prototype.funA = function() {
// Calling overridden funA function
Parent.prototype.funA.call(this);
print('GrandChild.funA called');
};
// ******* USAGE *******
var grandChild = new GrandChild('a','b', 'c');
grandChild.funA();
grandChild.funB();