Js繼承_個(gè)人心得記錄

繼承

    // 繼承
    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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容