js面向对象举例

<!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>

 

posted @ 2012-03-17 19:04  水之原  阅读(366)  评论(0编辑  收藏  举报