首页 > 技术文章 > JS继承方式

fanzhikang 2020-03-15 13:48 原文

原型链继承

//定义一个父类
function Father(name) {
    this.name = name;
    this.age = 20;
}
Father.prototype.say = function () {
    console.log(this.name);
}

//定义一个子类
function Child(name,age) {
    this.name = name;
    this.age = age
}

//最重要的一步,将父类的实例为子类的原型
Child.prototype = new Father();
let child1 = new Child('Marry',10);
let child2 = new Child('luccy',17);

缺点:

  1. 子类毕竟公用的是同一个父类,容易造成如果其中一个子类修改了原型上的内容,则其它的也会跟着一起更改
  2. 继承单一
  3. 新实例无法向父类实例,传参
    特点: 继承了父类的构造函数当中的属性,也继承了父类原型上的属性

构造函数继承

//定义一个父类
function Father(name) {
    this.name = name;
    this.age = 20;
}
Father.prototype.say = function () {
    console.log(this.name);
}

//定义一个子类
function Child(name,age) {
    Father.call(this,'father');
    this.name = name;
    this.age = age
}

let child1 = new Child('Marry',10);
let child2 = new Child('luccy',17);

缺点:

  1. 没有办法继承父类原型上的内容
  2. 无法实现构造函数复用
  3. 每个新实例否有父类构造函数的副本

优点:

  1. 可以向父级构造函数进行传参
  2. 可以继承多个构造函数属性

组合继承(构造函数继承 + 原型链继承)

//定义一个父类
function Father(name) {
    this.name = name;
    this.age = 20;
}
Father.prototype.say = function () {
    console.log(this.name);
}

//定义一个子类
function Child(name,age) {
    Father.call(this,'father');
    this.name = name;
    this.age = age
}
Child.prototype = new Father();
let child1 = new Child('Marry',10);
let child2 = new Child('luccy',17);

特点:

  1. 既可以继承父类的原型上的属性,又可以继承父类构造函数当中的属性
  2. 可继承,可复用
    缺点: 毕竟调用了两次父类的构造函数,会有性能上的影响

原型式继承

//定义一个父类
function Father(name) {
    this.name = name;
    this.age = 20;
}
Father.prototype.say = function () {
    console.log(this.name);
}

//这里是核心步骤
function content(obj) {
    function F() {};
    F.prototype = obj;
    return new F();
}

var sup = content(new Father())

缺点:

  1. 所有实例都会继承原型上的属性
  2. 无法实现复用(新实例属性都是后添加的)

寄生式继承

//定义一个父类
function Father(name) {
    this.name = name;
    this.age = 20;
}
Father.prototype.say = function () {
    console.log(this.name);
}


function content(obj) {
    function F() {};
    F.prototype = obj;
    return new F();
}

function a() {
    var sup = content(new Father());
    sup.name = 'Tom'
    return sup;
}

var child1 = a();


缺点: 没有用到原型,无法复用

寄生组合式

函数的原型等于另一个实例

在函数中用apply或者call引入另一个构造函数

//定义一个父类
function Father(name) {
    this.name = name;
    this.age = 20;
}
Father.prototype.say = function () {
    console.log(this.name);
}


function content(obj) {
    function F() {};
    F.prototype = obj;
    return new F();
}

function Child(name) {
    Father.call(this,'father');
    this.name = name;
}
var sup = new Father();
Child.prototype = content(sup);
sup.constructor = Child;

var child1 = new Child('Marry')

博客原文https://www.cnblogs.com/ranyonsue/p/11201730.html

推荐阅读