繼承
// 繼承
class Person{
constructor(name){
this.name = name
}
drink(){
console.log("喝水")
}
}
// 學(xué)生類(lèi) 繼承了Person的name屬性和drink函數(shù)
class Student extends Person{
// 構(gòu)造函數(shù)
constructor(name,age){
// 調(diào)用父類(lèi)的構(gòu)造函數(shù)
super(name)
this.age = age
}
// 學(xué)生的自我介紹函數(shù)
studentInfo(){
console.log(`我叫${this.name},年齡${this.age}`)
}
}
const student1 = new Student("小明",18)
student1.studentInfo()
student1.drink()
console.log(`————————————————`)
// 教師類(lèi) 繼承了Person的name屬性和drink函數(shù)
class Tearch extends Person{
// 構(gòu)造函數(shù)
constructor(name,salary){
// 調(diào)用父類(lèi)的構(gòu)造函數(shù)
super(name)
this.salary = salary
}
// 教師的自我介紹函數(shù)
tearchInfo(){
console.log(`我叫${this.name},工資${this.salary}`)
}
}
const tearch1 = new Tearch("王二",2000)
tearch1.tearchInfo()
tearch1.drink()
使用場(chǎng)景:兩個(gè)類(lèi)中如果存在相同屬性或函數(shù)的情況(name),可以創(chuàng)建一個(gè)父類(lèi)來(lái)繼承相同屬性或函數(shù)
參考視頻
參考地址 (轉(zhuǎn)載):https://www.bilibili.com/video/BV1Q64y1v7fW?p=1&vd_source=7a9ee67ca4d1e90007c9d660ba6f04b5