类与ES6类之间的继承

简介: 类与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('哈喽!');
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
● 和之前一样,我们创建一个学生的类继承Personcl,并且学生也有自己独特的属性

class StudentCl extends PersonCl {}

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

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

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

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

const ItShare = new StudentCl('IT share', 2001, '计算机科学与技术');
console.log(ItShare);
1
2
3
4
5
6
7
8
9
10

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

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();
1
2
3
4
5
6
7
8
9
10
11
12
13

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

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();
1
2
3
4
5
6
7
8
9
10
11
12
13
14

相关文章
|
3月前
|
JavaScript 前端开发
es6 类与继承
ES6 的类与继承特性使得 JavaScript 的面向对象编程更加规范和易于维护,提高了代码的可读性和可复用性,广泛应用于各种复杂的 JavaScript 应用程序开发中。
|
5月前
es5 类与继承
es5 类与继承
31 0
|
6月前
|
Java
继承与组合的区别
【8月更文挑战第22天】
194 0
|
9月前
|
JavaScript 前端开发
ES6如何声明一个类?类如何继承?
ES6如何声明一个类?类如何继承?
57 0
2.【类的组合(在一个类中定义一个类)】
2.【类的组合(在一个类中定义一个类)】
67 0
|
C++ 小程序
c++类的实例化,有没有new的区别
A a; A * a = new a(); 以上两种方式皆可实现类的实例化,有new的区别在于: 1.前者在堆栈中分配内存,后者为动态内存分配,在一般应用中是没有什么区别的,但动态内存分配会使对象的可控性增强。
1285 0
普通类,抽象类和接口之间的区别
普通类,抽象类和接口之间的区别
|
C#
类的定义
类的定义
156 0

热门文章

最新文章