JS面向对象模拟动物继承

JS面向对象模拟动物继承

动物继承
    <script>

        /*Animal构造函数*/
        function Animal(name,color,legNum){
            this.name=name;
            this.color=color;
            this.legNum=legNum;
        }

        /*Animal往原型上添加方法*/

        Animal.prototype.eat=function (food) {
            console.log(`${this.name}喜欢吃${food}`);
        }

        /*继承构造函数的方法*/
        Cat.prototype=new Animal();
        Dog.prototype=new Animal();

         /*继承构造函数的参数,继承Animal的属性*/
        /*构造Cat函数*/
       function Cat(name,color,legNum,hobby) {
           /*把Animal的属性都继承过来,现在改变this指向,注意这里的是this指的是Cat对象,arguments指的是name,color,legNum*/
           Animal.apply(this,arguments);
           /*注意自己新增的新特性要写在参数的最后*/
           this.hobby=hobby;
       }

       function Dog(name,color,legNum,hobby) {
           Animal.apply(this,arguments);
           this.hobby=hobby;
       }

        Cat.prototype.yield=function () {
            console.log(`${this.color}的${this.name},有${this.legNum}条腿,它的兴趣是:${this.hobby}喜欢对着人喵喵叫!`);
        }

        Dog.prototype.yield=function () {
            console.log(`${this.color}的${this.name},有${this.legNum}条腿,它的兴趣是:${this.hobby}喜欢对着人汪汪叫!`);
        }

        var cat= new Cat("猫","白色","4","懒洋洋睡觉!");
        var dog= new Dog("狗","黄色","4","喜欢看门");


        /*白色的猫,有4条腿,喜欢吃鱼,它的兴趣是:懒洋洋睡觉!*/
          cat.eat("鱼");
          /*黄色的狗,有4条腿,喜欢吃骨头,它的兴趣是:喜欢看门*/
          dog.eat("骨头");
          dog.yield();
          cat.yield();

    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值