【问题标题】:Why does I need .prototype in superClass.prototype when extends it?为什么我在扩展时需要在 superClass.prototype 中使用 .prototype?
【发布时间】:2018-05-25 20:02:14
【问题描述】:

为什么我需要在扩展Shape.prototype 中使用.prototype

// Shape — superClass
function Shape() {
  this.x = 0;
  this.y = 0;
  }

Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Figure has rode out somewhere.');
};

function Rectangle() {
  Shape.call(this); 
}

Rectangle.prototype = Object.create(Shape.prototype);//<<<=HERE

我的意思是这个“Shape.prototype”。 为什么我需要使用原型而不只是形状?据我所知 .prototype 包含类的继承属性和方法。我的 Shape 类是基本类,没有继承属性。

【问题讨论】:

  • 我的 Shape 类是基本的,没有继承的属性。 当然可以 - 它继承自 Object。现在,如果您希望您的Rectangle 继承Shapexy 属性,则需要将Rectangle.prototype 设置为Shape 的新实例。另外,不要将Classprototype 混淆。使用您的代码,根本没有类,所以最好不要讨论这个词。
  • 问题不在于Shape 是否继承了任何东西。您使用new Shape 创建的所有对象都继承自Shape

标签: javascript class object inheritance prototype


【解决方案1】:

方法通常被添加到对象的底层原型中,这样它们就不必存储在以后生成的每个实例中。在此示例中就是这种情况,move() 函数存储在Shape.prototype 中。

如果您不将Shape.prototypeObject.create() 一起使用,您将不会获得附加到该对象的方法继承到Rectangle

从技术上讲,您可以只使用 Object.create(Shape),但仅在 Shape 仅直接附加实例属性的情况下,即使在这种情况下,它也不是一个非常可扩展的解决方案,因为如果您决定返回并在将来向Shape.prototype 添加方法,您的子类型都不会继承它。

// Shape — superClass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// Shape.prototype is a unique and specific instance of Object
// This particular instance is what Shape inherits from and is
// the reason why Shape will get a .toString() and a .valueOf()
// method.
console.log(Shape.prototype);

// This method is added to Shape.prototype. If you don't inherit
// from this, you won't inherit this method!!
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Figure has rode out somewhere.');
};

function Rectangle() {
  Shape.call(this); 
}

// If we don't inherit from Shape.prototype, we won't get
// any of the methods attached to it!
Rectangle.prototype = Object.create(Shape); 

var r = new Rectangle();

console.log(r.x, r.y);  // Works just fine for instance properties attached direclty to Shape
r.move(10,20);          // Fails because Shape.prototype wasn't used for inheritance!

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多