1.我们先定义一个学生 类 输入姓名,得分
class Student {
constructor(name, score) {
this.name = name;
super(name)
this.score = score;
}
introduce() {
console.log(`我是${this.name},我考了${this.score}`);
}
}
const student = new Student('gyb', 99)
student.introduce(); //我是gyb,我考了99
console.log(student); //Student {name: "gyb", score: 99}
2.我们定义一个老师类 输入姓名 学科
class Teacher {
constructor(name, subject) {
this.name = name;
super(name)
this.subject = subject;
}
introduce() {
console.log(`我是${this.name},我教${this.subject}`);
}
}
const teacher = new Teacher('小马哥', '前端开发')
teacher.introduce() //我是小马哥,我教前端开发
console.log(teacher); //Teacher {name: "小马哥", subject: "前端开发"}
- 我们发现上面的两个类方法, 老师和学生都用共同的构造属性 this.name = name ,那么我们就可以用class继承父级的够着函数 用extends 和super( )实现继承
同时继承以后,也可以实现调用父级的方法 hobby
注意 被继承的类必须先声明再被继承
class Person {
constructor (name){
this.name = name
}
hobby(){
console.log('我是自愿的');
}
}
class Student extends Person {
constructor(name, score) {
// this.name = name; //继承父级的 这里就不需要了
super(name) //用super 继承父级的构造函数
this.score = score;
}
introduce() {
console.log(`我是${this.name},我考了${this.score}`);
}
}
const student = new Student('gyb', 99)
student.introduce()
student.hobby()
console.log(student);
class Teacher extends Person {
constructor(name, subject) {
// this.name = name;
super(name)
this.subject = subject;
}
introduce() {
console.log(`我是${this.name},我教${this.subject}`);
}
}
const teacher = new Teacher('小马哥', '前端开发')
teacher.introduce()
console.log(teacher);
teacher.hobby()
练习案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/*
总结,
1.类中的构造器不是必须写的,要对实例进行一些初始化的操作才使用到, 如添加指定属性时
2.如果A类继承B类,且A类总写了构造器,那么A类中的super是必须调用的.
3.类中所定义的方法,都是放在了类的原型对象上,工实例去使用
*/
// 创建一个Person类
class Person {
constructor(name, age) {
//构造器中的this是谁, 类的实例对象
this.name = name
this.age = age
}
// 一般方法
speak() {
// speak方法放在了哪里?__类的原型对象上,供实例使用
// 通过Person实例调用speak,speak中的this就是Person实例
console.log(`我叫${this.name},我今年${this.age}`);
}
}
//创建一个Student类,继承于Person类
class Student extends Person {
constructor(name, age, grade) {
super(name, age)
this.grade = grade
}
//重写从父类继承过来的方法
speak() {
console.log(`我叫${this.name},我今年${this.age},我现在是${this.grade}`);
}
study(){
// study方法放在了哪里? 类的原型对象上,供实例使用
// 通过student实例调用study时,study中的this就是student实例
console.log('我的目标是学习');
}
}
let p1 = new Person('张三', 18)
console.log(p1);
p1.speak()
let s1 = new Student('李四', 19, '一年级')
console.log(s1);
s1.speak()
s1.study()
</script>
</body>
</html>