js中的各种继承

原型链继承
function Parent(name,age){
            this.name=name;
            this.age=age;
            this.subjects=['英语','数学','语文']
        }
        Parent.prototype.getname=function(){
            console.log(this.name);
        }
        function Child(){
            
        }
        Child.prototype=new Parent('张三',18);
        let c1=new Child();
        let c2=new Child();
        console.log(c1.name); //张三
        console.log(c2.name);  //张三

        // 修改c1.name
        c1.name='李四';
        console.log(c1.name); //李四
        console.log(c2.name); //张三

        c1.subjects.push('化学');
        console.log(c1.subjects); //['英语', '数学', '语文', '化学']
        console.log(c2.subjects);  //['英语', '数学', '语文', '化学']

        //以上可以看出,修改父亲的基本数据类型和引用数据类型时,情况不一样
        

在这里插入图片描述

构造函数
function Parent(name){
            this.name=name;
            this.speak=function(){
                console.log('speak');
            }
        }
        Parent.prototype.getname=function(){
            console.log('getname');
        }
        Parent.prototype.age='19';
        function Child(){
            Parent.call(this,"张三");
            this.sex='f'
        }
        let c1=new Child();
        console.dir(c1);

在这里插入图片描述
可见,通过构造函数进行继承,原型链上的属性和方法没法继承
在这里插入图片描述

组合继承
function Parent(){
            this.name='zyzy';
            this.speak=function(){
                console.log('speak');
            }
        }
        Parent.prototype.getname=function(){
            console.log('getname');
        }
        Parent.prototype.age='19';
        function Child(){
            Parent.call(this);  //构造函数
            this.sex='f'
        }
       Child.prototype=new Parent();  //原型链
        let c1=new Child();
        console.dir(c1);

在这里插入图片描述
在这里插入图片描述

原型式继承(对象继承)

在这里插入图片描述

在这里插入图片描述

寄生式组合继承
  function Parent(){
            this.name='zyzy';
            this.speak=function(){
                console.log('speak');
            }
        }
        Parent.prototype.getname=function(){
            console.log('getname');
        }
        Parent.prototype.age='19';

        function Child(){
            Parent.call(this);  
            this.sex='f'
        }

        function CreateObj(o){
            function F(){};
            F.prototype=o;
            return new F();
        }

        function extend(child,parent){
            child.prototype=Object.create(parent.prototype);
            child.prototype.constructor=child;
        }
       Child.prototype=new Parent();  
        let c1=new Child();
        console.dir(c1);
      

在这里插入图片描述

参考添加链接描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值