I need to do the following:
function Shape (width, height) {
var self = this;
self.width = width;
self.height = height;
self.calculateSurface = function () {
return (self.width * self.height);
};
};
function Circle (radius) {
//make sure width == height == radius.
};
Circle.prototype = new Shape;
Circle.prototype.constructor = Circle();
function Triangle (base, height) {
var self = this;
Shape.apply(self, arguments);
};
Triangle.prototype = new Shape;
Triangle.prototype.constructor = Triangle();
var circle = new Circle(5);
var triangle = new Triangle(5, 8);
alert(circle.calculateSurface());
alert(triangle.calculateSurface());
Both calls to the base prototype method must return the area of the caller, but without overriding the method.
How can I make it return (width * height) / 2 for triangle and (radius * radius) * pi for circle without overriding it?
Thanks for your time and all best!
EDIT:
var output = document.getElementById('output');
function Shape(width, height) {
var self = this;
self.width = width;
self.height = height;
};
Shape.prototype.calculateSurface = function () {
return (this.width * this.height);
};
function Rectangle(width, height) {
Shape.apply(this, arguments);
};
Rectangle.prototype = new Shape;
Rectangle.prototype.constructor = Rectangle;
function Triangle(base, height) {
Shape.apply(this, arguments);
};
Triangle.prototype = new Shape;
Triangle.prototype.constructor = Triangle;
Triangle.prototype.calculateSurface = function () {
return ((this.width * this.height) / 2);
};
function Circle(radius) {
Shape.apply(this, arguments);
};
Circle.prototype = new Shape;
Circle.prototype.constructor = Circle;
Circle.prototype.calculateSurface = function () {
return((this.width * this.width) * Math.PI);
};
// testing
var outputStr = "";
var outputArr = [];
for (var i = 0; i < 30; i++) {
var rectangle = new Rectangle(i + 1, i + 2);
var triangle = new Triangle(i + 1, i + 2);
var circle = new Circle(i + 1);
outputArr[i] = rectangle;
outputStr += "Rectangle width: <b>" + rectangle.width + "</b> height: <b>" + rectangle.height + "</b> area: <b>" + rectangle.calculateSurface() + "</b><br />";
outputArr[i + 1] = triangle;
outputStr += "Triangle base: <b>" + triangle.width + "</b> height: <b>" + triangle.height + "</b> area: <b>" + triangle.calculateSurface() + "</b><br />";
outputArr[i + 2] = circle;
outputStr += "Circle radius: <b>" + rectangle.width + "</b> area: <b>" + circle.calculateSurface() + "</b><br /><br />";
};
output.innerHTML = outputStr;
It works correctly, I hope I understood it right.
Thanks again!
First of all, you shouldn’t define method (
calculateSurface) of the custom type (a.k.a. “class”) on the instance, so, not:But:
Then you need to shadow the property that is higher in the prototype chain. So the lookup will first look at
Triangle.prototypeand only then atShape.prototype– using the first property it finds.Same goes for the
Circle.