我有以下代码:
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()
方法- 为什么
mySecondCircle
有calculateArea()
方法,但是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。