一个简单的题目:
写一个形状类,再写一个三角形类和一个矩形类,用面向对象的方式实现,输出各个形状的边数和面积。
三角形和矩形继承自形状类。
源码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
//-------------抽象类形状--------------
function Shape(edges) {
this.edges = edges;
}
//定义一个虚方法,用于重写
Shape.prototype.getArea = function () {
return -1;
}
Shape.prototype.getEdges = function () {
return this.edges;
}
//--------------三角形----------------
function Triangle(bottom, height) {
Shape.call(this, 3);
this.bottom = bottom;
this.height = height;
}
//继承
Triangle.prototype = new Shape();
//重写方法
Triangle.prototype.getArea = function () {
return 0.5 * this.bottom * this.height;
}
//---------------矩形----------------
function Rectangle(bottom, height) {
Shape.call(this, 4);
this.bottom = bottom;
this.height = height;
}
//继承
Rectangle.prototype = new Shape();
//重写方法
Rectangle.prototype.getArea = function () {
return this.bottom * this.height;
}
//-------------测试-------------------
var tri = new Triangle(4, 5);
document.write(tri.getEdges() + "<br>");
document.write(tri.getArea() + "<br>");
var rect = new Rectangle(20, 40);
document.write(rect.getEdges() + "<br>");
document.write(rect.getArea() + "<br>");
</script>
</body>
</html>