JavaScript: Diagramm zur Erläuterung der Vererbung, __proto__ und des Prototyps
Ich habe den folgenden Code:
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);
Ich hätte gerne eine visuelle * Erklärung von:
die Änderungen verursacht durchCircle.prototype = Object.create(Shape.prototype);
das__proto__
undprototype
Verbindungen zwischen den ObjektenWiemySecondCircle
erbt dasdescribeLocation()
Methode vonShape
warum zumcalculateArea()
Methode existiert fürmySecondCircle
aber nicht fürmyFirstCircle
:> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function
> mySecondCircle.calculateArea()
"My area is 314.1592653589793"
* Wenn Sie versuchen, JavaScript-Probleme in Bezug auf die Vererbung zu verstehen, ist ein Diagrammwert tausend wörter, und ich fand die Diagramme in diesen Fragen sehr hilfreich:1, 2, 3, 4.