JavaScript Es5继承以及Es6继承

Es5之前常用的三种继承

Es5继承 

原型链继承

//原型链继承
    //把父类的实力属性赋值给子类原型 , 就叫做原型链继承

    //父类
    function Fu(name) {
        this.name = name
        this.sleep = function () {
            console.log(this.name + "会飞");
        }
    }

    Fu.prototype.eat = function () {
        console.log(this.name + "会跑");
    }
    //子类

    function Zi() {
    }
    //子类继承父类
    Zi.prototype = new Fu('小明')
    let one = new Zi
    one.sleep()
    one.eat()
    console.log(one.name);

 构造函数继承

 //父类
    function Fu(name) {
        this.name = name
        this.sleep = function () {
            console.log(this.name + "会飞");
        }
    }
    Fu.prototype.eat = function(){
        console.log(this.name+"会跑"); //
    }
    //子类
    function Zi(name){
        Fu.call(this,name)
    }
    let one = new Zi('构造函数继承')
    console.log(one.name);
    one.sleep()
    //one.eat() // 报错  es5继承.html:102 Uncaught TypeError: one.eat is not a functionat 
                                                                                         
               

组合式继承

 // 组合式继承
    //原型链继承和构造函数继承的结合

    //优点 : 可以传参 可以继承原型上的实例属性

    // 父类
    function Fu(name) {
        this.name = name
        this.sleep = function () {
            console.log(this.name + "会飞");
        }
    }
    Fu.prototype.eat = function () {
        console.log(this.name + "会跑"); //
    }

    //子类
    function Zi(name){
        Fu.call(this,name)
    }

    Zi.prototype=new Fu()

    //修改constructor指针

    Zi.prototype.constructor=Zi

    let one = new Zi('组合式继承')

    console.log(one.name);

    one.eat()

    one.sleep()

Es6继承

class类 


    //es6的 class类  语法糖

    class Fu {
        constructor(name = "王", age = "18") {
            this.name = name
            this.age = age
        }
        eat() {
            console.log(`${this.name} ${this.age} eat food`);
        }
    }

    //继承父类
    class Zi extends Fu {
        constructor(name = "人", age = "20") {
            //继承父类属性
            super(name, age) //super指的是父亲的超集 people.call(this)
        }
        eat(){
            //继承父类方法
            super.eat()
        }
    }
    let ZiObj = new Zi('嘻嘻嘻')
    ZiObj.eat()
    console.log(ZiObj.name);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值