【js】原型继承和类继承写法

一段时间不用class就忘了咋使用了呜,记一下
原型继承写法:
function Father(name, age) {
        this.name = name;
        this.age = age;
      }
      Father.prototype = {
        // 重写的别忘了指回去,直接添加的不用
        constructor: Father,
        sing(song) {
          console.log(this.name + "已经" + this.age + "了,爱唱" + song);
        },
      };

      function Son(name, age, color) {
        // 用call方法将子级的this指向传给父级,改变了父级的this指向
        // 这样就继承了父级构造函数身上的属性方法
        Father.call(this, name, age);
        this.color = color;
      }

      // 利用原型继承
      Son.prototype = new Father();
      // 记得指回去
      Son.prototype.constructor = Son;

      const f = new Father("John", 34);
      f.sing("小星星");

      const s = new Son("Eve", 12, "pink");
      s.sing("孤勇者");
类继承写法:
// 利用super关键字继承,可以调用父类的构造函数,也可以调用父类的普通函数
      // super继承,在constructor中调用super,子类没有定义constructor方法,
      // super方法会被默认添加。子类的构造函数中,只有调用super之后,
      // 才可以使用this关键字,否则会报错。
      class Father {
        constructor(name, age) {
          this.name = name;
          this.age = age;
        }

        sing(song) {
          console.log(this.name + "已经" + this.age + "了,爱唱" + song);
        }
      }

      // 先用extends让子元素继承父类
      class Son extends Father {
        constructor(name, age, color) {
          // 使用super调用了父类中的构造函数
          super(name, age);
          this.color = color;
        }
        sing(song) {
          // super.sing() 调用父类的普通函数
          super.sing(song);
        }
      }

      const f = new Father("John", 34);
      f.sing("小星星");

      const s = new Son("Eve", 12, "pink");
      s.sing("孤勇者");
结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茄茄茄子eggplant

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值