JS继承

来源:互联网 发布:如何分析问卷调查数据 编辑:程序博客网 时间:2024/06/06 04:54

前言

整理总结下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实例的构造函数)。