js寄生组合式继承

813 阅读1分钟

寄生组合式继承强化的部分就是在组合继承的基础上减少一次多余的调用父类的构造函数:

function Animal(color) {
  this.color = color;
  this.name = 'animal';
  this.type = ['pig', 'cat'];
}

Animal.prototype.greet = function(sound) {
  console.log(sound);
}

function Dog(color) {
  Animal.apply(this, arguments);
  this.name = 'dog';
}

/* 注意下面两行 */
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.getName = function() {
  console.log(this.name);
}
var dog = new Dog('白色');   
var dog2 = new Dog('黑色');     
dog.type.push('dog');   
console.log(dog.color);   // "白色"
console.log(dog.type);   // ["pig", "cat", "dog"]
console.log(dog2.type);  // ["pig", "cat"]
console.log(dog2.color);  // "黑色"
dog.greet('汪汪');  //  "汪汪"

在上面的例子中,我们并不像构造函数继承一样直接将父类Animal的一个实例赋值给Dog.prototype,而是使用Object.create()进行一次浅拷贝,将父类原型上的方法拷贝后赋给Dog.prototype,这样子类上就能拥有了父类的共有方法,而且少了一次调用父类的构造函数。

Object.create()的浅拷贝的作用类式下面的函数:

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

这里还需注意一点,由于对Animal的原型进行了拷贝后赋给Dog.prototype,因此Dog.prototype上的constructor属性也被重写了,所以我们要修复这一个问题:

Dog.prototype.constructor = Dog;

文章内容转自 ghmagical.com/article/pag…