注册 登录
编程论坛 JavaScript论坛

prototype继承,,显示不出来呀

渐渐鱼 发布于 2018-06-24 17:08, 1673 次点击
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script>
        function Car()        //基类
        {
            this.color="white";
            this.size="middle";
            this.set=function set(color,size){this.color=color;this.size=size;}
            this.run=function(){return "I can run";}
            this.voice=function() {return "I can voice";}
        }
        function Bus()     //子类
        {
            Bus.prototype=new Car();
            Bus.prototype.constructor=Bus;
             this.kkk=function kkk(){return "KKK";}
        }
        function Truck()
        {
            Truck.prototype=new Truck();
            Truck.prototype.constructor=Truck;
            this.kkk=function kkk(){return "kkk";}
        }
        var bus=new Bus();
        bus.set("white","middle");
        alert(bus.color);
        alert(bus.run());
        var truck=new Truck();
        truck.set("grey","big");
        alert(truck.size);
        alert(truck.voice());
        </script>
    </body>
    </html>
2 回复
#2
林月儿2018-07-11 21:17
程序代码:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script>
        function Car()        //基类
        {
            this.color="white";
            this.size="middle";
            this.set=function set(color,size){this.color=color;this.size=size;}
            this.run=function(){return "I can run";}
            this.voice=function() {return "I can voice";}
        }
        function Bus()     //子类
        {
            //Bus.prototype.constructor=Bus;
            //this.kkk=function kkk(){return "KKK";}
        }
        Bus.prototype=new Car();
        function Truck()
        {
            //Truck.prototype.constructor=Truck;
            //this.kkk=function kkk(){return "kkk";}
        }
        Truck.prototype=new Car();
        var bus=new Bus();
        bus.set("white","middle");
        alert(bus.color);
        alert(bus.run());
        var truck=new Truck();
        truck.set("grey","big");
        alert(truck.size);
        alert(truck.voice());
        </script>
    </body>
    </html>
#3
leeqihero2018-07-24 17:46
<html>
<head>
<meta charset=utf-8>
</head>
<body>
<script>
Car={
    color:'white',
    size:'middle',
    run:function(){
        return 'I can run';
    },
    voice:function(){
        return 'I can voice';
    }
};
bus={__proto__:Car};
truck={color:'grey',size:'big',__proto__:Car};
console.log(bus.color);
console.log(bus.run());
console.log(truck.color);
console.log(truck.run());
</script>
</body>
</html>
1