当前位置: 首页 > news >正文

类与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();

在这里插入图片描述


http://www.mrgr.cn/news/13734.html

相关文章:

  • stm32启动文件
  • 您应该让 ChatGPT 控制您的浏览器吗?
  • 【Java设计模式】Builder模式:在Java中清晰构建自定义对象
  • 【ceph学习】ceph如何进行数据的读写(2)
  • 恶意软件分析与防御:网络安全技术的新篇章
  • Element-plus组件库基础组件使用
  • 解决Spring的代理失效问题
  • 零基础学习Redis(8) -- list类型命令使用
  • ubuntu jammy vagrant 国内源
  • [设计模式之抽象工厂模式—— 家具工厂]
  • 基于深度学习的游客满意度分析与评论分析【情感分析、主题分析】
  • Java设计模式之建造者模式详细讲解和案例示范
  • HTML沙漏爱心
  • SQL进阶技巧:如何查询最近一笔有效订单? | 近距离有效匹配问题
  • 云计算概述
  • Spring MVC常用注解及用法
  • 无人机挂载迫击炮吊舱设计技术详解
  • Selenium(HTML基础)
  • Vue 0_1项目实战
  • React -TS学习—— useRef