function Rectangle(width, height){
this.width = width;
this.height = height;
}
Rectangle.prototype.getArea = function(){
return this.width * this.height;
}
function Square(size){
this.width = size;
this.height= size;
}
// Square 继承 Rectangle
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
var square = new Square(5);
console.log(square instanceof Square); // true;
console.log(square instanceof Rectangle); // true
console.log(square.getArea());
为什么 Square
继承 Rectangle
时,不是用 Square.prototype
指向 Rectangle.prototype
,而是指向 Rectangle
的对象实例?(而实际上继承就是用 Square.prototype
指向 Rectangle.prototype
)。
如果:
那么对Square.prototype.getArea的修改就会影响到Rectangle.prototype.getArea;
就不会。