我需要执行以下操作:
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 for triangle 和 (radius * radius) * pi for circle 而不会覆盖它?
感谢您的时间,一切都好!
编辑:
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;
它工作正常,我希望我理解正确。 再次感谢!