【发布时间】: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继承Shape的x和y属性,则需要将Rectangle.prototype设置为Shape的新实例。另外,不要将Class与prototype混淆。使用您的代码,根本没有类,所以最好不要讨论这个词。 -
问题不在于
Shape是否继承了任何东西。您使用new Shape创建的所有对象都继承自Shape。
标签: javascript class object inheritance prototype