# 关于原型和继承

# 继承

  1. 原型链继承
function Parent() {
  this.shares = [];
}

Parent.prototype.getAge = function() {
  return this.age;
};
Parent.prototype.setAge = function(age) {
  this.age = age;
};

function Child() {}

Child.prototype = new Parent();

const me = new Child();
me.setAge(40);
console.log(me.getAge());
me.shares.push('apple');

const pig = new Child();
pig.shares.push('banana');
console.log(pig.getAge());
console.log(me.shares, pig.shares);

多个实例共享一个原型对象,数据之间相互影响。并且子类无法调用父类的构造函数,参数无法传递。

  1. 构造函数继承
function Parent() {
  this.shares = [];
}

Parent.prototype.getAge = function() {
  return this.age;
};
Parent.prototype.setAge = function(age) {
  this.age = age;
};

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

const me = new Child();
// me.setAge(40);
// console.log(me.getAge());
me.shares.push('apple');

const pig = new Child();
pig.shares.push('banana');
// console.log(pig.getAge());
console.log(me.shares, pig.shares);

在构造函数中直接调用父类函数,可以实现向父类传递参数。

  1. 组合继承
  2. 原型式继承
  3. 寄生式继承
  4. 寄生组合式继承