当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js中的四种继承方式

js中的四种继承方式

2020年07月26日  | 移动技术网IT编程  | 我要评论

什么是继承

在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.csdn.net/a_l_f_/article/details/107559509

本文地址:https://blog.csdn.net/niceer8/article/details/107573893

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网