JavaScript中的继承

1 什么是继承

        继承是一种类(class)与类之间的关系,JS中没有类,但是可以通过构造函数模拟类,然后通过原型来实现继承。

为什么要使用继承呢,是因为它有如下几个优点

  • 继承是为了实现数据共享,js中的继承当然也是为了实现数据共享。
  • 继承是子类继承父类的特征或者行为,使子类也具有父类的属性和方法;
  • 或者子类从父类继承方法,使得子类具有父类相同的行为
  • 继承可以使得子类具有父类的各种属性和方法,而不需要再次编写相同的代码。

2.通过原型实现继承

原型链继承是比较常见的继承方式之一

复制代码
  function Parent1() {
    this.name = 'parent1';
    this.play = [1, 2, 3]
  }

  function Child1() {
    this.type = 'child2';
  }

  Child1.prototype = new Parent1();
  console.log(new Child1());
复制代码

3.构造函数继承(借助 call)

复制代码
  function Parent1(){
    this.name = 'parent1';
  }

  Parent1.prototype.getName = function () {
    return this.name;
  }

  function Child1(){
    Parent1.call(this);
    this.type = 'child1'
  }

  let child = new Child1();
  console.log(child);  // 没问题
  console.log(child.getName());  // 会报错
复制代码

4.组合继承(前两种组合)

复制代码
  function Parent3 () {
    this.name = 'parent3';
    this.play = [1, 2, 3];
  }


  Parent3.prototype.getName = function () {
    return this.name;
  }

  function Child3() {
    // 第二次调用 Parent3()
    Parent3.call(this);
    this.type = 'child3';
  }


  // 第一次调用 Parent3()
  Child3.prototype = new Parent3();
  // 手动挂上构造器,指向自己的构造函数
  Child3.prototype.constructor = Child3;
  var s3 = new Child3();
  var s4 = new Child3();
  s3.play.push(4);
  console.log(s3.play, s4.play);  // 不互相影响
  console.log(s3.getName()); // 正常输出'parent3'
  console.log(s4.getName()); // 正常输出'parent3'
复制代码

5.原生性继承

复制代码
  let parent4 = {
    name: "parent4",
    friends: ["p1", "p2", "p3"],
    getName: function() {
      return this.name;
    }
  };


  let person4 = Object.create(parent4);
  person4.name = "tom";
  person4.friends.push("jerry");


  let person5 = Object.create(parent4);
  person5.friends.push("lucy");


  console.log(person4.name);
  console.log(person4.name === person4.getName());
  console.log(person5.name);
  console.log(person4.friends);
  console.log(person5.friends);
复制代码

从上面的代码中可以看到,通过 Object.create 这个方法可以实现普通对象的继承,不仅仅能继承属性,同样也可以继承 getName 的方法,请看这段代码的执行结果。

以上就是我理解的几种继承方式。

posted @   &三分野  阅读(116)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示