Constructor inheritance is done through resetting the prototype from constructor.
function Rectangle(length, width) {
this.length = length; //from w ww . j av a 2 s .co m
this.width = width;
}
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
Rectangle.prototype.toString = function() {
return "[Rectangle " + this.length + "x" + this.width + "]";
};
// Square inherits from Rectangle
function Square(size) {
this.length = size;
this.width = size;
}
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
Square.prototype.toString = function() {
return "[Square " + this.length + "x" + this.width + "]";
};
var rect = new Rectangle(5, 10);
var square = new Square(6);
console.log(rect.getArea()); // 50
console.log(square.getArea()); // 36
console.log(rect.toString()); // "[Rectangle 5x10]"
console.log(square.toString()); // "[Square 6x6]"
console.log(rect instanceof Rectangle); // true
console.log(rect instanceof Object); // true
console.log(square instanceof Square); // true
console.log(square instanceof Rectangle); // true
console.log(square instanceof Object); // true
The code above generates the following result.
You simply call the supertype constructor from the subtype constructor using either call() or apply() to pass in the newly created object. In effect, you're stealing the supertype constructor for your own object, as in this example:
function Rectangle(length, width) {
this.length = length; /*w w w . j a va 2 s .com*/
this.width = width;
}
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
Rectangle.prototype.toString = function() {
return "[Rectangle " + this.length + "x" + this.width + "]";
};
// inherits from Rectangle
function Square(size) {
Rectangle.call(this, size, size);
// optional: add new properties or override existing ones here
}
Square.prototype = Object.create(Rectangle.prototype, {
constructor : {
configurable : true,
enumerable : true,
value : Square,
writable : true
}
});
Square.prototype.toString = function() {
return "[Square " + this.length + "x" + this.width + "]";
};
var square = new Square(6);
console.log(square.length); // 6
console.log(square.width); // 6
console.log(square.getArea()); // 36
The code above generates the following result.