一、使用class实现继承
1.class 的使用
class Student {
constructor (name, score){
this.name = name;
this.score = score
}
introduce () {
console.log(`我的名字是${this.name},我的成绩是${this.score}`)
}
}
const student = new Student("张三","99");
student.introduce() // 打印结果为 我的名字是张三,我的成绩是99
2.继承 extends
新建class
class Teacher {
constructor (name, subject){
this.name = name;
this.subject = subject
}
teach () {
console.log(`我的名字是${this.name},我教的科目是${this.subject}`)
}
}
const teacher = new Teacher("王老师","语文");
teacher.teach() // 打印结果为 我的名字是王老师,我教的科目是语文
Teacher类与Student类有共同属性name ,可以把共同属性提出来创建父级类,让Teacher和Student继承
// 父类
class Person {
constructor (name,){
this.name = name
}
}
// 学生类
class Student extends Person { // 通过关键字extends关键字继承Person
constructor (name, score){
super(name) // 通过super关键字
this.score = score
}
teach () {
console.log(`我的名字是${this.name},我的成绩是${this.score}`)
}
}
const student = new Student("张三","99");
student.teach() // 打印结果为 我的名字是张三,我的成绩是99
// 老师类
class Teacher extends Person {
constructor (name, subject){
super(name) // 通过super关键字
this.subject = subject
}
teach () {
console.log(`我的名字是${this.name},我教的科目是${this.subject}`)
}
}
const teacher = new Teacher("王老师","语文");
teacher.teach() // 打印结果为 我的名字是王老师,我教的科目是语文
同样的 父类中的方法也可以继承,如果父类中有方法 drink():
// 父类
class Person {
constructor (name,){
this.name = name
}
drink () {
console.log("喝水")
}
}
//上述代码中 Student和Teacher已经继承了 Person,所以在new实例后可以直接调用drink函数
student.drink() // 喝水
teacher.drink() // 喝水
二、什么是原型
定义了Student类
class Student {
constructor (name, score){
this.name = name;
this.score = score
}
teach () {
console.log(`我的名字是${this.name},我的成绩是${this.score}`)
}
}
const student = new Student("张三","99");
student.teach() // 打印结果为 我的名字是张三,我的成绩是99
//可以通过student.name 访问 student的name属性
当通过 student.teach() 时可以调用,在控制台打印 student时 teach方法放在__proto__中,这个__proto__指向的就是示例的原型,即Student类中的 Student.prototype。
student.__proto__ === Student.protoType // true
三、原型链
// 父类
class Person {
constructor(name) {
this.name = name
}
}
// 老师类
class Teacher extends Person {
constructor(name, subject) {
super(name) // 通过super关键字
this.subject = subject
}
teach() {
console.log(`我的名字是${this.name},我教的科目是${this.subject}`)
}
}
const teacher = new Teacher("王老师", "语文");
teacher.teach() // 打印结果为 我的名字是王老师,我教的科目是语文
当在控制台打印示例teacher时:
即一级一级链上去,
teacher.hasOwnProperty("name") // true
teacher.hasOwnProperty("teach") // false
此方法判断是否是自己的属性还是原型链里的属性