组件化开发-02-类与继承-(二)-类的继承——必须在构造函数的第一行调用super, super函数的作用:调用父类构造函数初始化父类的数据

本文详细阐述了在JavaScript中,如何在类的继承构造函数中正确使用super,以及其作用是初始化父类数据。通过实例演示了如何在`Person`和`Student`类中实现继承并展示属性。

类的继承——必须在构造函数的第一行调用super, super函数的作用:调用父类构造函数初始化父类的数据

  • 类的继承
    • super表示父类的构造函数,用于向父类传递参数
    • 必须在第一行调用super
   class TypeStudent extends Student {
      constructor (uname, age, type) {
        // super表示父类的构造函数,用于向父类传递参数
        // 必须在第一行调用super
        super(uname, age);
        this.type = type;
      }
      showType () {
        console.log(this.type)
      }
    }

    let ts = new TypeStudent('lisi', 11, '三好学生');
    ts.showInfo();
    ts.showType();
实例
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <script type="text/javascript">
    /*
    类的继承 extends
  */
    class Person {
      constructor(uname, age) {
        this.uname = uname;
        this.age = age;
      }
      showAge() {
        console.log(this.age)
      }
    }
    class Student extends Person {
      constructor(uname, age, score) {
        // 必须在构造函数的第一行调用super
        // super函数的作用:调用父类构造函数初始化父类的数据
        super(uname, age);
        this.score = score;
      }
      showScore() {
        console.log(this.score)
      }
    }
    var stu = new Student('lisi', 15, 100)
    console.log(stu)
    stu.showScore()
    stu.showAge()
  </script>
</body>

</html>

显示

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值