- Objective:
- Breadcrumb:
# 概念阐释
## 语义
`extends`用来创建一个子类。在有的情况下,类会分享一些共同的属性和不同的属性,我们可以先创建一个父类,填写共同的部分,再创建一个子类,填写不同的部分。
`super` 关键字调用父类中的构造方法。
## 语法
```js
class ChildClass extends ParentClass {
constructor(parentClass, childClass) {
super(parentClass);
this._childClass = childClass;
}
}
```
- extends 关键字允许使用父类中的内容;
- super关键字调用父类中的构造方法`constructor()`; **super必须永远放在第一个,否则会JS会抛出错误**
# 实例

#### 父类
和普通对象没区别。
```js
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0; // 数值时一个衡量,不需要写参数名
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
```
#### 子类
用extends和super
```js
class Cat extends Animal {
constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
get usesLitter(){
return this._usesLitter;
}
}
```
```js
class Animal {
constructor(name){
this.name=name;
}
speak(){
console.log("I am a "+this.name);
}
}
class Dog extends Animal {
constructor(name,trainer) {
super(name);
this.trainer = trainer;
}
speak() {
super.speak();
console.log("My trainer is " + this.trainer);
}
}
const rover = new Dog("Lab","Terry");
rover.speak(); //调用了 animal 的 speak 方法
//结果
"I am a Lab"
"My trainer is Terry"
```
如果主类有多个参数,子类的constructor和super中都要写。
#### 创建实例
```js
const bryceCat = new Cat('Bryce', false);
console.log(bryceCat.name); // output: Bryce
```
# 相关内容
# 问题
- [练习题5](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-javascript-syntax-part-iii/modules/wdcp-22-learn-javascript-syntax-classes-8d95f6d1-ff64-43c3-8ff7-cdc933e16fde/lessons/classes/exercises/inheritance-v)
# 问题答案
```js
class HospitalEmployee {
constructor(name) {
this._name = name;
this._remainingVacationDays = 20;
}
get name() {
return this._name;
}
get remainingVacationDays() {
return this._remainingVacationDays;
}
takeVacationDays(daysOff) {
this._remainingVacationDays -= daysOff;
}
}
// Nurse 子类,certifications属性
class Nurse extends HospitalEmployee {
constructor(name,certifications) {
super(name);
this._certifications = certifications;
}
get certifications() {
return this._certifications;
}
//在certifications getter下添加一个名为addCertification的方法。该方法应该接受一个输入参数(newCertification)。在方法内部,使用push方法将newCertification的值添加到护士的certifications数组中。
addCertification(newCertification) {
this._certifications.push(newCertification);
}
}
// 创建一个nurseOlynyk实例,名字为Olynyk,认证有'Trauma','Pediatrics',计算剩余休假时间,和print认证
const nurseOlynyk = new Nurse('Olynyk',['Trauma','Pediatrics']);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);
console.log(nurseOlynyk.certifications);
//调用addCertification(newCertification)方法,添加Genetics,一个新的认证
nurseOlynyk.addCertification('Genetics');
console.log(nurseOlynyk.certifications);
```
# 参考资料
- [extends-MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/extends)