總結各類奇葩原型繼承,面試向

 

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)

相關文章
相關標籤/搜索