I have the following 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);
I'd like a visual* explanation of:
- the changes caused by
Circle.prototype = Object.create(Shape.prototype);
- the
__proto__
andprototype
connections between the objects - how
mySecondCircle
inherits thedescribeLocation()
method fromShape
- why the
calculateArea()
method exists formySecondCircle
but not formyFirstCircle
:
> myFirstCircle.calculateArea()
Uncaught TypeError: undefined is not a function
> mySecondCircle.calculateArea()
"My area is 314.1592653589793"
* When trying to understand JavaScript issues regarding inheritance, a diagram really is worth a thousand words, and I've found the diagrams in these questions very helpful: 1, 2, 3, 4.