首先了解一下super的用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//super关键字
class Person {
constructor(username, age) {
this.username = username;
this.age = age;
}
say() {
return this.username + "," + this.age
}
}
class Student extends Person {
constructor(username, age, score) {
super(username, age)
//子类继承父类的时候,第一行必须要写super 调用了父类的构造函数来去实例化子类本身。
this.score = score
}
say() {
return super.say() + "," + this.score
}
}
let stu = new Student("张三", 18, 40)
console.log(stu.say())
</script>
</body>
</html>
总结一下:
通过代码可以看出,super 调用了父类的构造函数来去实例化子类本身,
如果用到了constructor就要写super(),是用来初始化this的,可以绑定事件到this上,
如果在constructor中要使用this.props,就必须给super加参数:super(props)。