总结js各种继承

51 阅读1分钟
1. 原型链继承:把父类实例放到子类原型上。
    //1.原型链继承
    function Animal() {
      this.kind = '动物';
    }

    Animal.prototype.eat = function () {
      console.log('eat');
    }

    function Cat() {
      this.age = 1;
    }

    Cat.prototype = new Animal();

    var cat = new Cat();
    console.log(cat.kind); // 输出:动物
    cat.eat(); // 输出:eat

2. 构造函数继承:通过在子类中通过改变this指向复用父类的构造函数来实现继承。
function Parent() {
  this.name = 'Parent';
}

Parent.prototype.sayHello = function() {
  console.log('Hello');
}

function Child() {
  Parent.call(this);
  this.age = 18;
}

var child = new Child();
console.log(child.name); // 输出:Parent
child.sayHello(); // 报错:child.sayHello is not a function
//只是通过改变this指向给Child构造函数用了Parent方法所以和Parent的原型无关。
3. 组合继承:通过结合原型链继承和构造函数继承来实现继承,在子类构造对象时可以通过call给复用的父类构造函数传参。
function Parent() {
  this.name = 'Parent';
}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

const child = new Child();
console.log(child.name); // 输出 "Parent"

4. 原型式继承:通过创建一个临时的构造函数来实现继承。
function createObj(o) {
  function F() {}
  F.prototype = o;
  return new F();
}

const parent = {
  name: 'Parent'
};

const child = createObj(parent);
console.log(child.name); // 输出 "Parent"

5. 寄生式继承:在原型式继承的基础上,增强对象,返回一个具有附加属性和方法的对象。
function createObj(o) {
  const clone = Object.create(o);
  clone.sayHello = function() {
    console.log('Hello');
  }
  return clone;
}

const parent = {
  name: 'Parent'
};

const child = createObj(parent);
console.log(child.name); // 输出 "Parent"
child.sayHello(); // 输出 "Hello"

6. 组合寄生式继承:通过借用构造函数继承属性和方法,并利用原型链继承原型上的方法。
function Parent() {
  this.name = 'Parent';
}

function Child() {
  Parent.call(this);
}

function inheritPrototype(child, parent) {
//以下三条语句实现了原型的逻辑闭环了
  const o = Object.create(parent.prototype);
  o.constructor = child;
  child.prototype = o;
}

inheritPrototype(Child, Parent);

const child = new Child();
console.log(child.name); // 输出 "Parent"