借用构造函数和组合继承

2019-07-14  本文已影响0人  南蓝NL

借用构造函数(伪造对象或经典继承)

基本思想:在子类型构造函数的内部调用超类型的构造函数
优点: 相比原型链而言,借用构造函数有一个很大的优势,就是子类型函数构造函数可以向超类型构造函数传递参数
缺点: 方法都在构造函数中定义,因此函数的复用性就无从谈起了

function  Animal(speices){
  this.speices = speices;
}

function Dog(){
  Animal.call(this,'中华田园犬');  //  dog拥有了animal中的name属性
}

var dog1 = new Dog();
var dog2 = new Dog();
console.log(dog1.speices);  //  中华田园犬

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

function Animal(speices){
  this.speices = speices;
  this.skills = ["jump","climb","catch","run"]
}

Animal.prototype.getSpeices = function(){
  console.log(this.speices)
}

function Dog(speices,color){
  // 借用构造函数继承,继承父类的属性
  Animal.call(this,speices);
  this.color = color;
}

// 原型继承,继承父类的方法
Dog.prototype = new Animal();

Dog.prototype.getColors = function(){
  console.log(this.colors);
}

var dog1 = new Dog('博美','white');
dog1.skills.push('acting');
console.log(dog.skills);  //  ["jump","climb","catch","run","acting"]
dog1.getSpeices();  // 博美

var dog2 = new Dog('柯基','brown');
console.log(dog2.skills); //  ["jump","climb","catch","run"]
dog2.getSpeices();  // 柯基

组合继承融合借用构造函数(属性继承)和原型链继承(方法继承)的优点,使实例都有自己的属性,又能共享统一方法,成为最常用的继承方法

上一篇 下一篇

猜你喜欢

热点阅读