ES6中的类(class),构造方法(controctor)和类的继承(super)及实例化(new)

17 阅读1分钟
<script>
  //定义一个类
  class People {
    // 构造方法
    constructor(name, age, sex) {
      this.name = name;
      this.age = age;
      this.sex = sex;
    }
  }

  //   老师类继承自人类
  class Teacher extends People {
    // 开始构造方法
    constructor(name, age, sex, rank, salary) {
      // 从人类继承了name age sex
      super(name, age, sex);
      this.rank = rank;
      this.salary = salary;
    }
    // 直接在类里添加自我介绍方法
    introduce() {
      console.log(
        `大家好,我叫${this.name},性别${this.sex},年龄${this.age},担任${this.rank},工资${this.salary}`
      );
    }
  }

  //   实例化老师类
  const zhangsanqiang = new Teacher("张三强", "男", 55, "系主任", 5000);
  //   调用老师的自我介绍方法
  zhangsanqiang.introduce();
</script>