类与ES6类之间的继承

前言

● 下面是之前学习ES6 classes的代码

class PersonCl {
  constructor(fullName, birthYear) {
    this.fullName = fullName;
    this.birthYear = birthYear;
  }

  calcAge() {
    console.log(2037 - this.birthYear);
  }

  greet() {
    console.log(`你好${this.fullName}`);
  }

  get age() {
    return 2037 - this.birthYear;
  }

  set fullName(name) {
    if (name.includes(' ')) this._fullName = name;
    else alert(`${name} is not a full name!`);
  }

  get fullName() {
    return this._fullName;
  }

  //静态方法
  static hey() {
    console.log('哈喽!');
  }
}

● 和之前一样,我们创建一个学生的类继承Personcl,并且学生也有自己独特的属性

class StudentCl extends PersonCl {}

const ITshare = new StudentCl('IT share', 2001);

我们即使没有写任何的构造函数,也可以直接继承父类

在这里插入图片描述

● 现在我们尝试写构造函数来给学生赋予新的属性,并且可以让学生继承父类的方法

class StudentCl extends PersonCl {
  constructor(fullName, birthYear, course) {
    //总是需要首先书写
    super(fullName, birthYear);
    this.course = course;
  }
}

const ItShare = new StudentCl('IT share', 2001, '计算机科学与技术');
console.log(ItShare);

在这里插入图片描述

● 可以像上一章一样再学生类中添加新的方法

class StudentCl extends PersonCl {
  constructor(fullName, birthYear, course) {
    //总是需要首先书写
    super(fullName, birthYear);
    this.course = course;
  }
  introduce() {
    console.log(`我的名字叫${this.fullName},我的专业是${this.course}`);
  }
}

const ItShare = new StudentCl('IT share', 2001, '计算机科学与技术');
ItShare.introduce();

在这里插入图片描述

● 当然,父类中的计算年龄的方法也同样适用

class StudentCl extends PersonCl {
  constructor(fullName, birthYear, course) {
    //总是需要首先书写
    super(fullName, birthYear);
    this.course = course;
  }
  introduce() {
    console.log(`我的名字叫${this.fullName},我的专业是${this.course}`);
  }
}

const ItShare = new StudentCl('IT share', 2001, '计算机科学与技术');
ItShare.introduce();
ItShare.calcAge();

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值