JavaScript: diagrama para explicar herança, __proto__ e protótipo
Eu tenho o seguinte 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);
Eu gostaria de uma explicação visual * de:
as mudanças causadas porCircle.prototype = Object.create(Shape.prototype);
a__proto__
eprototype
conexões entre os objetosquãomySecondCircle
herda odescribeLocation()
método deShape
porque ocalculateArea()
existe um método paramySecondCircle
mas não paramyFirstCircle
:> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function
> mySecondCircle.calculateArea()
"My area is 314.1592653589793"
* Ao tentar entender os problemas de JavaScript relacionados à herança, um diagrama é realmentevale mais que mil palavras, e achei os diagramas nestas perguntas muito úteis:1, 2, 3, 4.