JS实现继承的几种方式及优缺点

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>

  <script>
    //类的声明与实例化
    function Animal1() {
      this.name = name;
    }
    class Animal2 {
      constructor() {
        this.name = name;
      }
    }
    console.log(new Animal1(), new Animal2());

    //借助构造函数实现继承
    function Parent1() {
      this.name = 'parent1';
    }
    function Child1() {
      Parent1.call(this); //将父级构造函数的this指向子构造函数实例上
      this.type = 'child1';
    }
    console.log(new Child1());
    //缺点:无法实现父类原型链上的属性和方法,只实现了部分继承

    //借助原型链实现继承
    function Parent2() {
      this.name = 'parent2';
      this.play = [1, 2, 3];
    }
    function Child2() {
      this.type = 'child2';
    }
    Child2.prototype = new Parent2();
    var s1 = new Child2();
    var s2 = new Child2();
    s1.play.push(4);
    console.log(s1.play, s2.play);
    // 缺点:一个子类的实例原型从父类构造函数中继承来的共有属性就会直接影响到其他子类

    //组合方式
    function Parent3() {
      this.name = 'parent3';
      this.play = [1, 2, 3];
    }
    function Child3() {
      Parent3.call(this);
      this.type = 'child3';
    }
    Child.prototype = new Parent();
    var s3 = new Child3();
    var s4 = new Child3();
    s3.play.push(4);
    console.log(s3.play, s4.play);
    //缺点:父构造函数执行了两次(没必要)

    //组合继承的优化一
    function Parent4() {
      this.name = 'parent4';
      this.play = [1, 2, 3];
    }
    function Child4() {
      Parent3.call(this);
      this.type = 'child4';
    }
    Child.prototype = Parent.prototype;
    var s5 = new Child4();
    var s6 = new Child4();
    s5.play.push(4);
    console.log(s5.play, s6.play);

    console.log(s5 instanceof Child4, s5 instanceof Parent4);
    //缺点:无法区分一个实例是子构造器还是父构造器的实例

    //组合继承的优化二
    function Parent5() {
      this.name = 'parent4';
      this.play = [1, 2, 3];
    }
    function Child5() {
      Parent3.call(this);
      this.type = 'child4';
    }
    Child5.prototype = Object.create(Parent5.prototype);
    Child5.prototype.constructor = Child5;
    var s7 = new Child5();
    console.log(s7 instanceof Child4, s7 instanceof Parent4);
    console.log(s7.constructor);
  </script>
  
</body>

</html>

  

转载于:https://www.cnblogs.com/wzp-monkey/p/10481117.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值