【发布时间】:2015-05-23 05:45:36
【问题描述】:
我有以下代码:
function Shape(x, y) {
this.x = x;
this.y = y;
}
Shape.prototype.describeLocation = function() {
return 'I am located at ' + this.x + ', ' + this.y;
};
var myShape = new Shape(1, 2);
function Circle(x, y, radius) {
Shape.call(this, x, y); // call parent constructor
this.radius = radius;
}
var myFirstCircle = new Circle(3, 4, 10);
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.calculateArea = function() {
return 'My area is ' + (Math.PI * this.radius * this.radius);
};
var mySecondCircle = new Circle(3, 4, 10);
我想要一个直观的*解释:
-
Circle.prototype = Object.create(Shape.prototype);引起的变化 -
__proto__和prototype对象之间的联系 -
mySecondCircle如何从Shape继承describeLocation()方法 - 为什么
calculateArea()方法适用于mySecondCircle而不适用于myFirstCircle:
> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function
> mySecondCircle.calculateArea()
"My area is 314.1592653589793"
* 当试图理解有关继承的 JavaScript 问题时,图表确实是 worth a thousand words, 我发现这些问题中的图表非常有帮助: 1, 2, 3, 4.
【问题讨论】:
-
哦,这是一个不错的图表链接集合 :-)
标签: javascript inheritance prototype