经典问题 2小解 - 继承

// 写一个形状类, 再写一个三角形类和一个矩形类, 用面向对象的方式实现, 输出各个形状的边数和面积。
        // 三角形和矩形继承自形状类。
        
        // function Shape(){ 
        //     console.log(this.side);
        //     console.log(this.area);
        // }
        // function Triangle(width,height){            
        //     this.side=3;
        //     this.area=width*height*0.5;
        //     Shape.call(this);
        // }
        // function Rectangle(width,height){            
        //     this.side=4;
        //     this.area=width*height;
        //     Shape.call(this);
        // }
        // new Triangle(1,2);
        // new Rectangle(1,2);

        function Shape() {}
        Shape.prototype.side = function () {
            throw Error('side');
        }
        Shape.prototype.area = function () {
            throw Error('area');
        }

        function Triangle(width, height) {
            this.width = width;
            this.height = height;
        }
        Triangle.prototype = new Shape();
        Triangle.prototype.side = function () {
            console.log('3');
        }
        Triangle.prototype.area = function () {
            console.log(this.width * this.height * 0.5);
        }

        new Triangle(1, 2).side(); //3
        new Triangle(1, 2).area(); //1

        function Rectangle(width, height) {
            this.width = width;
            this.height = height;
        }
        Rectangle.prototype = new Shape();
        new Rectangle(1, 2).side();

猜你喜欢

转载自www.cnblogs.com/justSmile2/p/9937021.html