类的继承——必须在构造函数的第一行调用super, super函数的作用:调用父类构造函数初始化父类的数据
- 类的继承
- super表示父类的构造函数,用于向父类传递参数
- 必须在第一行调用super
class TypeStudent extends Student {
constructor (uname, age, type) {
// super表示父类的构造函数,用于向父类传递参数
// 必须在第一行调用super
super(uname, age);
this.type = type;
}
showType () {
console.log(this.type)
}
}
let ts = new TypeStudent('lisi', 11, '三好学生');
ts.showInfo();
ts.showType();
实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
/*
类的继承 extends
*/
class Person {
constructor(uname, age) {
this.uname = uname;
this.age = age;
}
showAge() {
console.log(this.age)
}
}
class Student extends Person {
constructor(uname, age, score) {
// 必须在构造函数的第一行调用super
// super函数的作用:调用父类构造函数初始化父类的数据
super(uname, age);
this.score = score;
}
showScore() {
console.log(this.score)
}
}
var stu = new Student('lisi', 15, 100)
console.log(stu)
stu.showScore()
stu.showAge()
</script>
</body>
</html>
显示

本文详细阐述了在JavaScript中,如何在类的继承构造函数中正确使用super,以及其作用是初始化父类数据。通过实例演示了如何在`Person`和`Student`类中实现继承并展示属性。
-类的继承——必须在构造函数的第一行调用super, super函数的作用:调用父类构造函数初始化父类的数据&spm=1001.2101.3001.5002&articleId=113449634&d=1&t=3&u=e085e6d9e55845f59744403aae808d4b)
843

被折叠的 条评论
为什么被折叠?



