ES6的方法改写prototype实例

32 阅读1分钟
<script>
  // 定义一个人类
  class people {
    // 实例化时执行构造方法
    constructor(name, age, sex) {
      this.name = name;
      this.age = age;
      this.sex = sex;
    }
    // 这个类有一个introduce方法
    introduce() {}
  }

  //   定义一个学生类,继承自人类
  class Student extends people {
    // 构造一个方法
    constructor(name, age, sex, hobby) {
      //   使用super
      // 作为函数使用, 代表父类的构造方法, 只能用在子类的构造方法中,
      super(name, age, sex);
      // 这是自类的私有属性
      this.hobby = hobby;
    }
    //   这个子类有一个自我介绍方法
    introduce() {}
  }

  //   定义一个老师类,继承自分类,老师类也有自己的私有属性和方法
  class Teacher extends people {
    // 构造一个方法
    constructor(name, age, sex, rank, salary) {
      super(name, age, sex);
      this.rank = rank;
      this.salary = salary;
    }
    introduce() {
      console.log(
        `我是${this.name}老师, 性别${this.sex}, ${this.age}岁, 现担任${this.rank}一职, 工资到手${this.salary}, 我很幸福`
      );
    }
  }

  //   定义一个小学生类继承自学生类
  class pupil extends Student {
    constructor(name, age, sex, hobby, birthday) {
      super(name, age, sex, hobby);
      this.birthday = birthday;
    }
    introduce() {}
  }
  //   定义一个大学生类继承自学生类
  class Undergraduate extends Student {
    constructor(name, age, sex, hobby, major, school, loverName) {
      super(name, age, sex, hobby);
      this.major = major;
      this.school = school;
      this.loverName = loverName;
    }
    introduce() {}
  }
  // 实例化一个类
  const zhangsanqiang = new Teacher("张三强", 53, "男", "系主任", 1800);
  zhangsanqiang.introduce();
</script>