JavaScript:解释继承的图表,__ proto__和原型

Tac*_*tex 4 javascript inheritance prototype

我有以下代码:

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);
Run Code Online (Sandbox Code Playgroud)

我想要一个视觉*解释:

  • 由...引起的变化 Circle.prototype = Object.create(Shape.prototype);
  • __proto__prototype 中的对象之间的连接
  • 如何从中mySecondCircle继承describeLocation()方法Shape
  • 为什么该calculateArea()方法存在mySecondCircle但不适用于myFirstCircle:

> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function

> mySecondCircle.calculateArea()
"My area is 314.1592653589793"
Run Code Online (Sandbox Code Playgroud)

*如果想了解关于继承的JavaScript的问题,图真的是 胜过千言万语,我已经发现了这些问题的图表非常有帮助: 1, 2, 3, 4.

Tac*_*tex 13

图 全尺寸 - 图像,页面.

Circle.prototype(原始)被创建为副作用function Circle(...) {...}

Circle.prototype(重新定义)由.创建Circle.prototype = Object.create(Shape.prototype);


我还制作了这个动画版本来显示创建对象的顺序:

动画图 全尺寸 - 图像,页面.