ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaScript中的继承

2022-05-13 00:05:03  阅读:184  来源: 互联网

标签:function console name 继承 getName JavaScript log


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 的方法,请看这段代码的执行结果。

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

标签:function,console,name,继承,getName,JavaScript,log
来源: https://www.cnblogs.com/1499821416w/p/16265016.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有