【JS第29期】繼承-組合、原型式繼承

組合繼承

組合繼承就是使用原型鏈實現對原型的屬性和方法的繼承,經過借用構造函數來實現對實例屬性的繼承。如:前端

function SuperType(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

SuperType.prototype.sayName = function() {
  console.log(this.name)
}

function SubType(name, age) {
  SuperType.call(this, name);
  this.age = age;
}
// 繼承方法

SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function() {
  console.log(this.age)
}

var instance = new SubType('bill', 20);
instance.colors.push('black'); 
instance.colors // 'red', 'blue', 'green', 'black'
instance.sayName(); // 'bill'

var isntance2 = new SubType('bill2', 22);
instance2.colors // 'red', 'blue', 'green'
instance2.sayName(); // 'bill2'
複製代碼

上期中借用構造函數遺留問題是:方法定義在構造函數中,方法沒法複用。咱們這起經過組合繼承解決了這種問題,實現了方法複用。bash

原型式繼承

原型式繼承藉助原型能夠給予已有的對象建立新對象,同時還沒必要所以建立自定義類型。具體以下:函數

function object(o) {
  function F(){}
  F.prototype = o;
  return new F();
}
複製代碼

在object() 函數內部,先建立了一個臨時性的構造函數,而後將傳入的對象做爲這個構造函數的原型,最後返回了這個臨時類型的一個新實例。ui

var persion = {
  name: 'bill',
  friends: ['one', 'two', 'three']
};

var anotherPersion = object(persion);
anotherPersion.name = 'bill2';
anotherPersion.friends.push('four');

var yetAnotherPersion = object(persion);
yetAnotherPersion.name = 'bill3'
yetAnotherPersion.friends.push('five');

persion.friends; // 'one', 'two', 'three', 'four', 'five'
複製代碼

原型式繼承要求必須有一個對象能夠做爲另外一個對象的基礎。若是有這麼一個對象的話,能夠把它傳遞給object()函數,而後再根據具體需求對獲得的對象加以修改便可。this

ECMAScript 5 新增了object.create() 方法規範了原型繼承,具體以下:spa

var persion = {
  name: 'bill',
  friends: ['one', 'two', 'three']
};

var anotherPersion = object.create(persion);
anotherPersion.name = 'bill2';
anotherPersion.friends.push('four');

var yetAnotherPersion = object.create(persion);
yetAnotherPersion.name = 'bill3'
yetAnotherPersion.friends.push('five');

persion.friends; // 'one', 'two', 'three', 'four', 'five'
複製代碼

若有侵權,請發郵箱至wk_daxiangmubu@163.com 或留言,本人會在第一時間與您聯繫,謝謝!! prototype

關注咱們
長按二維碼關注咱們,瞭解最新前端資訊
相關文章
相關標籤/搜索