JS继承有哪些方式

 

方式一:es6继承

<script>
    class Parent{
        constructor(){
            this.age = 18;
        }
    }
    class Child{
        constructor(){
            this.name = '张山';
        }
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' undefined
</script>
<script>
    class Parent{
        constructor(){
            this.age = 18;
        }
    }
    class Child extends Parent{
        constructor(){
            super();
            this.name = '张山';
        }
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

方式二:原型链继承

        1、如果父类实例的属性是引用类型的时候,其实父类的实例属性会成为子类的原型属性,子类创建的所有实例都会共享这些方法,修改一个实例的这个属性,其他实例的属性也会被修改。

        2、子类型在实例化时不能给父类型的构造函数传参。

<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        this.name = '张山';
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' undefined
</script>
<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        this.name = '张山';
    }
    Child.prototype = new Parent();
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

方式三:借用构造函数

        1、只能在构造函数中调用方法 函数不能重用 就是每次子类生成实例的时候都会生成一次属性和方法。
        2、子类无法访问到父类原型上的方法。

<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        this.name = '张山';
        Parent.call(this);
    }
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

方式四:组合继承

        调用了两次父类构造函数 比较耗内存。

<script>
    function Parent(){
        this.age = 18;
    }
    function Child(){
        //借用构造函数
        Parent.call(this)
        this.name = '张山';
    }
    //原型链继承
    Child.prototype = new Parent();
    let o1 = new Child();
    console.log(o1.name,o1.age);//'张山' 18
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值