構(gòu)造函數(shù)繼承是通過從構(gòu)造函數(shù)重置原型來完成的。
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
上面的代碼生成以下結(jié)果。
您可以使用call()或apply()從子類型構(gòu)造函數(shù)調(diào)用超類型構(gòu)造函數(shù)傳入新創(chuàng)建的對(duì)象。 實(shí)際上,你“偷了超類構(gòu)造函數(shù)為您自己的對(duì)象,如在這個(gè)例子:
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
上面的代碼生成以下結(jié)果。
更多建議: