js中的四种继承方式

什么是继承

在js中,继承是通过原型链来实现的。就是子类去继承父类的公有属性和私有属性。根据创建对象的方式的不同,则他实现继承的方式也不一样。

js中创建对象的方式:

  1. 字面量方式。也就是直接创建对象
  2. 构造器+原型的方式。

继承的四种方式

原型继承

方法:子类的一个原型指向父类的一个方法
关键代码:Child.prototype=new Parent;

  function Parent(){
                this.x=100;
            }
            Parent.prototype.getX=function(){
                return this.x;
            }
            function Child(){
                this.y=200;
            }
            Child.prototype=new Parent;
            Child.prototype.getY=function(){
                return this.y;
            }
            let c1=new Child();
            console.log(c1.x);
            console.log(c1.y)
            console.log(c1.getX());
            console.log(c1.getY());
            

结果如下:在这里插入图片描述

call继承

方法:通过call来改变父函数中的this指向
关键代码:Parent.call(this);

function Parent(){
              this.x=100;
          }
          Parent.prototype.getX=function(){
              return this.x;
          }
          function Child(){
              Parent.call(this);
              this.y=200;
          }
          var c=new Child();
          console.log(c.x);
          console.log(c.y);
          

结果如下:在这里插入图片描述
当使用new开辟了一个新的空间,会让(this)中的this指向这个新的空间,然后call会改变父类中的this指向,也指向这个新的空间,这样父类的私有属性就会被继承过来,但是父类的公有属性不会被继承。
当我们输出c.getX:
在这里插入图片描述
结果:在这里插入图片描述

组合式继承

方法:把父类的私有属性和公有属性通过两行代码获取

function Parent() {
                this.x = 100;
            }
            Parent.prototype.getX = function () {
                return this.x;
            }
            function Child() {
                Parent.call(this);
                this.y = 200;
            }
            //Child.prototype=Parent.prototype//这样写不好,因为这样写子类会影响到父类,所以我们可以将父类的原型对象复制一份给子类
            //可以使用Object.create()来复制父类的原型对象
            Child.prototype = Object.create(Parent.prototype)
            Child.prototype.constructor = Child;//复制父类的原型对象后,子类原型对象中的constructor会被覆盖,所以最好手动更改一下constructor的指向。
            var c = new Child();
            console.log(c.x);
            console.log(c.y);

结果如下:在这里插入图片描述

ES6中的继承

ES6中的书写方式已经很想java了。

关键代码:extends和super().

class Parent{
               constructor(){
                   this.x=100;
               }
               getX(){
                   return this.x;
               }
           }
           class Child extends Parent{
               constructor(){
                   super();
                   this.y=200;
               }
               getY(){
                   return this.y
               }
           }
          var child=new Child();
          console.log(child.x);
          console.log(child.y);
          console.log(child.getX());

结果如下:
在这里插入图片描述

想学习更多关于ES6的知识,请关注:https://blog.youkuaiyun.com/a_l_f_/article/details/107559509

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值