Combination Inheritance
Description
Combination inheritance combines prototype chaining and constructor stealing to get the best of each approach.
Combination inheritance uses prototype chaining to inherit properties/methods on the prototype and uses constructor stealing to inherit instance properties.
Example
This allows function reuse by defining methods on the prototype and allows each instance to have its own properties. Consider the following:
function Shape(name){//from w w w.jav a 2 s .c o m
this.name = name;
this.colors = ["red", "blue", "green"];
}
Shape.prototype.sayName = function(){
console.log(this.name);
};
function Rectangle(name, width){
//inherit properties
Shape.call(this, name);
this.width = width;
}
//inherit methods
Rectangle.prototype = new Shape();
Rectangle.prototype.printWidth = function(){
console.log(this.width);
};
var instance1 = new Rectangle("Rect1", 10);
instance1.colors.push("black");
console.log(instance1.colors);
instance1.sayName();
instance1.printWidth();
var instance2 = new Rectangle("Rect2", 2);
console.log(instance2.colors);
instance2.sayName();
instance2.printWidth();
The code above generates the following result.