Javascript构造函数继承
2018-01-06 19:14 更新
Javascript面向对象设计 - Javascript构造函数继承
构造函数继承是通过从构造函数重置原型来完成的。
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
上面的代码生成以下结果。
构造函数偷
您可以使用call()或apply()从子类型构造函数调用超类型构造函数传入新创建的对象。 实际上,你“偷了超类构造函数为您自己的对象,如在这个例子:
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
上面的代码生成以下结果。
以上内容是否对您有帮助:
更多建议: