总结各类奇葩原型继承,面试向

 

1. 原型链继承函数

function Brother(name){this

  this.name = name;url

  this.wives = ["奶茶"];prototype

  this.marry = function(){};对象

}继承

function Employee(name) {dns

  this.name = name;原型链

}get

Employee.prototype = new Brother();原型

优势:书写简单

缺点: 没法给父类构造函数传参,子类会继承父类的全部引用类型,一旦原地修改就会影响全部子类。

const brother = new Brother("刘强东");

const employee1 = new Employee("刘强东的兄弟");

const employee2 = new Employee("刘强东的兄弟2");

console.log(employee1.wives); // 奶茶

console.log(employee2.wives); // 奶茶

employee1.wives.push("绿茶");

console.log(employee1.wives); // 奶茶,绿茶

console.log(employee2.wives); // 奶茶,绿茶

employee1.wives = ["绿茶"]; // 指向不一样对象

console.log(employee1.wives); // 绿茶

console.log(employee2.wives); // 奶茶,绿茶

 

2.借用构造函数

function Brother(name){

  this.name = name;

  this.wives = ["奶茶"];

      this.marry = function(){};

}

function Employee(name, age) {

  Brother.call(this, name);

  this.age = age;

}

缺点:父类方法内的函数每次都会生成新的拷贝;经过prototype定义的方法没法继承

 

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

function Brother(name){

  this.name = name;

  this.wives = ["奶茶"];

}

Brother.prototype.marry = function() {}

function Employee(name, age) {

  Brother.call(this, name);

  this.age = age;

}

Employee.prototype = new Brother();

缺点: 屡次调用构造函数

 

4.原型式继承  duck type 鸭式辨型

function object(o) {

  function F(){}

  F.prototype = o;

  return new F();

}

或者直接object.create(o);

使用场合:不必构建构造函数,仅仅是想模拟一个对象的时候

缺点:同原型链

5.寄生继承

function(original){

  newObj = Object(original)

  newObj.newFunc =(){}

  return newObj

}

 

缺点:方法在函数中定义,没法获得复用

6.寄生组合

function inheritPrototype(subType, supType) {

  var p = Object(supType.prototype);

  p.constructor = subType;

  subType.prototype = p;

}

function subType(){

  supType.call(this);

}

inheritProptype(subType, supType)

相关文章
相关标签/搜索