ES6基础入门(五)—— class继承及案例

1.class继承的实现

2.super关键字

3.方法的重写

<script>
    //es5
    
function Animal(name,color){
    this.name = name;
    this.color = color;
}
Animal.prototype.eat = function(){
    console.log(this.name + "is eating" );  //兔八哥is eating
}
Animal.prototype.sleep = function(){
    console.log(this.name + "is sleeping");  //兔八哥is sleeping
}

//继承
function Rabbit(name,age,color){
    //调用父类构造函数
    Animal.apply(this,arguments);
    this.age = age;
}
//通过原型传递
function foo(){};
foo.prototype = Animal.prototype;
Rabbit.prototype = new foo();
Rabbit.prototype.constructor = Rabbit;

let rabbit = new Rabbit("兔八哥","white",10);
rabbit.eat();
rabbit.sleep();
console.log(rabbit); //Rabbit {name: "兔八哥", color: "white", age: "white"}
    
    //es6:更简洁、直观
    class Animal{
    constructor(name,color){
        this.name = name;
        this.color = color;
    }
    eat(){
        console.log(this.name + "is eating" ); //兔八哥is sleep
    }
    sleep(){
        console.log(this.name +"is sleep");  //兔八哥is eating
    }
}

class Rabbit extends Animal{
    constructor(name,color,age){
        //子类中通过super调用父类的构造函数,一定要放在第一行
        // super访问父类的方法
        super(name,color);
        this.age = age;
    }
    //子类通过定义同名的方法覆盖父类中的方法,当子类对象调用的时候,优先执行子类自己拥有的方法
    eat(){
        console.log("露出了常常的牙齿")  // 露出了常常的牙齿
    }
    test(){
        //通过super关键字,调用父类对象中的方法
        super.eat();
    }
}
let rab = new Rabbit("兔八哥","白色",10);
rab.eat();
rab.sleep();
rab.test();
console.log(rab); //Rabbit {name: "兔八哥", color: "白色", age: 10}
</script>

《待更新》

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值