javascript中实现继承的示例

来源:互联网 发布:捕蜂器淘宝 编辑:程序博客网 时间:2024/05/17 23:41
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>对象继承的示例</title>
    <script type="text/javascript">
        //对象继承的示例
        //NaN 是 Not a Number的意思
        function Shape(edge) {
            this.edge = edge;
        }
        Shape.prototype.getArea = function() {
            return -1;
        }
        //三角形
        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;
        }
        
        Triangle.prototype.getEdge = function() {
            return this.edge;
        }
        
        var triangle = new Triangle(10, 4);

        alert(triangle.getEdge());
        alert(triangle.getArea());

        //四边形
        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;
        }

        Rectangle.prototype.getEdge = function() {
            return this.edge;
        }
        var rectangle = new Rectangle(20, 40);
        alert(rectangle.getEdge());
        alert(rectangle.getArea());

    </script>
</head>
<body>

</body>
</html>
0 0
原创粉丝点击