javascript原生原型:扩展、添加和覆盖方法

javascript native prototype: extend, add and overwrite methods?

本文关键字:添加 覆盖 方法 扩展 原生 原型 javascript      更新时间:2023-09-26

如何扩展原型并向其中添加新方法?例如,我想将Shape(超类)扩展为一个子类-Rectangle。我之所以扩展它,是因为我想使用Shape中的方法,但Rectangle中添加了更多方法(以及覆盖一些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.'

你知道我错过了什么吗?

您在此处覆盖Rectangle.prototype

Rectangle.prototype = {
    jump : function(){
        return 'Shape jumped';
    }
};

您应该添加以下内容:

Rectangle.prototype.jump = function(){
  return 'Shape jumped';
}