次のことを行う必要があります。
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());
ベース プロトタイプ メソッドへの両方の呼び出しは、呼び出し元の領域を返す必要がありますが、メソッドをオーバーライドすることはありません。
オーバーライドせずに、三角形の場合は (width * height) / 2 を、円の場合は (radius * radius) * pi を返すにはどうすればよいですか?
お時間をありがとうございました。
編集:
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;
正しく動作します。正しく理解できたと思います。 再度、感謝します!