如何扩展原型并在其中添加新方法?例如,我想将 Shape (超类)扩展为子类 - Rectangle 。我正在扩展它,因为我想使用 Shape 中的方法,但是添加更多方法(并且覆盖一些 Shape 矩形。
中的>方法但在矩形,
中添加方法后,我无法再次使用/访问 Shape 中的方法// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype = {
jump : function(){
return 'Shape jumped';
}
};
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle)); // true
console.log('Is rect an instance of Shape? ' + (rect instanceof Shape)); // true
rect.move(1, 1); // TypeError: rect.move is not a function
我追求的结果,
// Outputs, 'Shape moved.'
我错过了哪些想法?
答案 0 :(得分:5)
您在此处覆盖Rectangle.prototype
:
Rectangle.prototype = {
jump : function(){
return 'Shape jumped';
}
};
你应该添加它:
Rectangle.prototype.jump = function(){
return 'Shape jumped';
}