JavaScript三种继承方法

这篇博客探讨了JavaScript中的三种继承方式:经典继承、原型链继承和ES6的extends继承。经典继承通过Father.call()实现属性继承,原型链继承通过Son.prototype = new Father()建立联系,但会改变constructor,需要手动修复。而ES6的extends关键字简洁地实现了继承,并能调用super进行父类构造函数的调用。
摘要由CSDN通过智能技术生成

1.经典继承又称为构造函数继承

<script>
      // 借用父构造函数继承属性
      // 1.父构造函数
      function Father(uname, age) {
        // this指向父构造函数的对象实例
        this.uname = uname;
        this.age = age;
      }
      Father.prototype.money = function () {
        console.log(100000);
      };
      // 2.子构造函数
      function Son(uname, age, score) {
        // 经典继承又称为构造函数继承
        // this指向子构造函数的对象实例
        Father.call(this, uname, age); //改变指向
        this.score = score;
      }

2.原型链继承

//Son.prototype = Father.prototype;//这样相当给地址,所以子改变,父也跟着改
      //原型链继承
      //子构造函数的原型指向父构造函数的原型对象
      Son.prototype = new Father(); // {}的用法,所以SOn的constructor被覆盖了,指向father
      // 所以需要手动指回
      Son.prototype.constructor = Son;
      // 子构造函数专门的方法
      Son.prototype.exam = function () {
        console.log("100分");
      };
      var son = new Son("刘德华", 18, 100);
      console.log(son);
      console.log(Father.prototype);
      console.log(Son.prototype.constructor);
    </script>

3.extends继承

<script>
      class Father {
        constructor(x, y) {
          this.x = x;
          this.y = y;
        }
        sum() {
          console.log(this.x + this.y);
        }
      }
      // 子类继承父类加法方法,同时  拓展减法方法
      class Son extends Father {
        constructor(x, y) {
          // 利用super 调用父类的构造函数
          //  super 必须在子类this之前调用
          super(x, y);
          (this.x = x), (this.y = y);
        }
        subtract() {
          console.log(this.x - this.y);
        }
      }
      var son = new Son(5, 3);
      son.subtract();
      son.sum();
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值