Js继承_个人心得记录

UncleCodeIP属地: 湖南
0.121字数 82

继承

    // 继承
    class Person{
        constructor(name){
            this.name = name
        }

        drink(){
            console.log("喝水")
        }
    }

    // 学生类 继承了Person的name属性和drink函数
    class Student extends Person{
        // 构造函数
        constructor(name,age){
            // 调用父类的构造函数
            super(name)
            this.age = age
        }
        // 学生的自我介绍函数
        studentInfo(){
            console.log(`我叫${this.name},年龄${this.age}`)
        }
    }
    const student1 = new Student("小明",18)
    student1.studentInfo()
    student1.drink()
console.log(`————————————————`)
    // 教师类 继承了Person的name属性和drink函数
    class Tearch extends Person{
        // 构造函数
        constructor(name,salary){
            // 调用父类的构造函数
            super(name)
            this.salary = salary
        }
        // 教师的自我介绍函数
        tearchInfo(){
            console.log(`我叫${this.name},工资${this.salary}`)
        }
    }
    const tearch1 = new Tearch("王二",2000)
    tearch1.tearchInfo()
    tearch1.drink()

使用场景:两个类中如果存在相同属性或函数的情况(name),可以创建一个父类来继承相同属性或函数

参考视频

参考地址 (转载):https://www.bilibili.com/video/BV1Q64y1v7fW?p=1&vd_source=7a9ee67ca4d1e90007c9d660ba6f04b5

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
1人点赞
总资产3共写了1.1W字获得32个赞共4个粉丝

推荐阅读更多精彩内容