JS继承

前言

整理总结下JS继承的几种方法,并分析各方法的优缺点。

一、构造函数

  function Parent1() {
    this.name = 'parent1';
  }

  Parent1.prototype.say = function () {
  };

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

  console.log(new Child1());  //Child1 {name: "parent1", type: "child1"}
  console.log(new Child1().say());  //Uncaught TypeError: xxx say is not a function

优点:继承了Parent1的name属性;
缺点:没有继承Parent1原型链上的方法。

二、原型链方法

  function Parent2() {
    this.name = 'parent2';
    this.play = [1, 2, 3];
  }

  Parent2.prototype.say = function () {
    console.log('Parent2 say');
  };

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

  Child2.prototype = new Parent2();

  var s1 = new Child2();
  s1.say();  //Parent2 say
  console.log(s1.name, s1.type); //parent2 child2
  var s2 = new Child2();
  s1.play.push(4);
  console.log(s1.play, s2.play);  //[1, 2, 3, 4]、[1, 2, 3, 4]

优点:不仅继承了Parent2的name、play属性而且继承了其原型链上的方法;
缺点:由于将Parent2的实例作为Child2的原型,导致所有Child2实例共享Parent2的属性方法,其中一个Child2实例改变了原型链上Parent2的实例属性,
其他实例会受到影响跟着改变。

三、组合方法

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

  function Child3 () {
    Parent3.call(this);
    this.type = 'child3';
  }

  Child3.prototype = new Parent3();

  var s3 = new Child3();
  var s4 = new Child3();
  s3.play.push(4);
  console.log(s3.play, s4.play); //[1, 2, 3, 4]、[1, 2, 3]

优点:避免了原型链方法中出现的实例间相互影响(调用Parent3.call(this)使得Child3实例上有play属性,不必找到原型链上);
缺点:每次得到一个Child3实例,都会调用两次Parent3函数。

四、组合方法(优化一)

  function Parent4 () {
    this.name = 'parent4';
    this.play = [1, 2, 3];
  }

  function Child4 () {
    Parent4.call(this);
    this.type = 'child4';
  }

  Child4.prototype = Parent4.prototype;

  var s5 = new Child4();
  var s6 = new Child4();
  console.log(s5); //Child4 {name: "parent4", play: [1, 2, 3] type: "child4"}
  console.log(s6); //Child4 {name: "parent4", play: [1, 2, 3] type: "child4"}
  console.log(s5 instanceof Child4, s5 instanceof Parent4); //true true
  console.log(s5.constructor); //Parent4() {this.name = 'parent4';this.play = [1, 2, 3];}

优点:避免了Parent4重复调用问题;
缺点:Child4实例的构造函数不是Child4,而是Parent4(其实这不是优化带来的问题,优化前同样存在这个问题)

五、组合方法(优化二)

  function Parent5 () {
    this.name = 'parent5';
    this.play = [1, 2, 3];
  }

  function Child5 () {
    Parent5.call(this);
    this.type = 'child5';
  }

  Child5.prototype = Object.create(Parent5.prototype);
  Child5.prototype.constructor = Child5;

  var s7 = new Child5();
  console.log(s7 instanceof Child5, s7 instanceof Parent5); //true true
  console.log(s7.constructor); //Child5() {Parent5.call(this);this.type = 'child5';}

优点:Child5实例的构造函数是Child5(这里采用Object.create方法而不是直接Parent4.prototype赋值,直接赋值会影响到Parent4实例的构造函数)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值