我有以下代码:
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 .
最佳答案
Circle.prototype(原始) 是作为 function Circle(...) {...}
Circle.prototype(重新定义) 由 Circle.prototype = Object.create(Shape.prototype);
我还制作了这个动画版本来显示对象的创建顺序:
关于JavaScript:解释继承、__proto__ 和原型(prototype)的图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155986/