JS高级十、继承

JS中的继承,表示子类去继承父类的属性。

  • 1、原型链继承:让Child去找Parent上的属性或方法,如果找到的是一个引用数据类型,实际上找到的是一个地址,子类对象通过这个地址修改了Parent上的数据,其它得到子类对象也受到影响。

2、构造函数继承(Call继承):将Parent上的属性和方法添加到Child身上。使用call来复制一遍Parent上的操作。

1、原型链继承

让子类的原型指向父类的对象:

Child.protorype = new Parent();

同时让子类的原型对象中的constructor有正确的指向:

Child.prototype.constructor = Child;
<script>
    function Parent(){
        this.name = "ParentName"
    }
    Parent.prototype.getName = function(){
        console.log(this.name);
    }
    function Child(){}

    //原型链继承
    Child.prototype = new Parent();
    Child.prototype.constructor = Child;

    let c = new Child;
    c.getName();  //可以访问
</script>

缺点:

  • 1、如果父中的数据类型是引用数据类型,子对象修改了,其他子对象也会受影响(父中的数据如果时引用数据类型会被所有的子共享)
  • 2、创建Child对象时不能传参

2、构造函数继承(call继承)

将Parent上的属性和方法添加到Child身上。使用call来复制一遍Parent上的操作。

<script>
    function Parent(){
        this.hobby = ["eat","run"];
        this.name = "parentName";
    }
    function Child(){
        //核心
        Parent.call(this);
    }
    let c1 = new Child();
    let c2 = new Child();
</script>

3、组合继承

将原型链继承和构造函数继承相结合

4、寄生组合继承

借助中间函数

function Temp(){ }
Temp.protorype = Parent.protorype;
Child.protorype = new Temp();
Child.protorype.constructor = Child;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值