扩展时为什么我需要在superClass.prototype中使用.prototype?

时间:2018-05-25 20:02:15

标签: javascript class object inheritance prototype

为什么在扩展它时需要在.prototype中使用Shape.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

我的意思是这个&#39; Shape.prototype&#39;。 为什么我需要使用原型而不仅仅是Shape?据我所知.prototype包含一个类的继承属性和方法。我的Shape类是基本类,没有继承属性。

1 个答案:

答案 0 :(得分:0)

通常会将方法添加到对象的基础原型中,以便不必将它们存储在稍后生成的每个实例中。在此示例中就是这种情况,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!