JavaScript: diagrama para explicar la herencia, __proto__ y prototipo
Tengo el siguiente código:
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);
Me gustaría una explicación visual * de:
los cambios causados porCircle.prototype = Object.create(Shape.prototype);
el__proto__
yprototype
conexiones entre los objetoscómomySecondCircle
hereda eldescribeLocation()
método deShape
porqué elcalculateArea()
el método existe paramySecondCircle
pero no paramyFirstCircle
:> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function
> mySecondCircle.calculateArea()
"My area is 314.1592653589793"
* Al intentar comprender los problemas de JavaScript con respecto a la herencia, un diagrama realmente esvale más que mil palabras, y he encontrado los diagramas en estas preguntas muy útiles:1, 2, 3, 4.