【问题标题】:javascript native prototype: extend, add and overwrite methods?javascript 原生原型:扩展、添加和覆盖方法?
【发布时间】:2015-02-06 18:37:44
【问题描述】:

如何扩展原型并向其中添加新方法?例如,我想将 Shape(超类)扩展为子类 - Rectangle。我正在扩展它,因为我想使用 Shape 中的方法,但 添加更多 方法(并覆盖 一些 Shape > 的方法)在 Rectangle 中。

但是在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.'

任何想法我错过了什么?

【问题讨论】:

  • 您没有运行您发布的代码。 rect instanceof Shape 返回 false(因为 Rectangle.prototype 不再继承自 Shape.prototype)。
  • 你是对的。我的错误...

标签: javascript prototype prototypal-inheritance


【解决方案1】:

你在这里覆盖Rectangle.prototype

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

您应该改为添加:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2020-07-29
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多