欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > 类与ES6类之间的继承

类与ES6类之间的继承

2025/3/14 11:38:25 来源:https://blog.csdn.net/weixin_42952508/article/details/141651341  浏览:    关键词:类与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();

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词