• js——继承


    原型继承

    1)核心: 将父类实例作为子类原型
    2)优点: 方法复用
    3)缺点:
    1、创建子类实例的时候,不能传参
    2、子类实例共享了父类的构造函数的引用属性,比如foods
    3、无法实现多继承

    		//父类
            function School(name,foods){
       
                this.name=name
                this.foods=['甜品']
                this.person=function(){
       
                    console.log(this.name+'吃'+this.foods);
                }
            }
            //父类原型对象添加方法
            School.prototype.print=function(){
       
                console.log(this.name,this.foods);
            }
            //子类
            function Student(){
       }
            //原型继承
            Student.prototype=new School()
            //纠正constructor指向
            Student.prototype.constructor=Student
            //创建实例
            let stu1=new Student()
            let stu2=new Student()
            stu1.name='jack'
            stu1.foods.push('罐头')
            console.log(stu1.name);
            console.log(stu1.foods);
            stu1.person()
            stu1.print()
            console.log('——————————————————————————————————————————————');
            stu2.name='rose'
            stu2.foods.push('香蕉')
            console.log(stu2.name);
            console.log(stu2.foods);
            stu2.person()  
            stu2.print()  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    构造函数继承

    1)核心: 借用父类的构造函数来增强子类实例,等于复制父类的实例属性给子类
    2)优点: 实例之间独立
    1、创建子类实例,可以向父类构造函数传参数。
    2、子类实例不共享父类的构造函数的引用属性。如foods属性
    3、可实现多继承(通过多个call或者apply继承多个父类)
    3)缺点
    1、父类的方法不能复用
    由于方法再父构造函数中定义,导致方法不能复用(因为每次创建子类实例都要创建一遍方法)
    2、子类实例,继承不了父类原型上的属性(因为没有用到原型)

    		function School(name,foods){
       
                this.nam
    • 1
    • 2
  • 相关阅读:
    Vue3中实现路由跳转的过渡动画(一)
    项目经理之如何组建跨部门项目团队
    Halcon · 曲线宽度检测算法总结
    C如何调用python
    Cypress学习记录之一:简介和安装
    探讨NLP对行业大量数据信息抽取的技术实现
    pg 时间操作方法
    【Python】Python 利用模块实现单例模式
    【无标题】
    Improving Few-Shot Learning with Auxiliary Self-Supervised Pretext Tasks(论文解读)
  • 原文地址:https://blog.csdn.net/weixin_46051260/article/details/126420400