DIV CSS 佈局教程網

淺談 JavaScript 實現繼承的三個演進階段
編輯:關於JavaScript     

JS 裡一切皆物件。那麼要讓子物件繼承父物件的屬性與方法,一開始我們會怎麼寫?考慮到原型的概念,最直覺的做法是這樣:

S1:直接讓子類原型等於父類實例

function Parent() {
  this.name = '123';
}
Parent.prototype.getName = function () {
  return this.name;
};

function Son() {
  this.age = 20;
}
Son.prototype = new Parent();
Son.prototype.getAge = function () {
  return this.age;
};

var son = new Son();
console.log('Name :' + son.getName() + ';Age: ' + son.getAge());
// Name :123;Age: 20

關鍵在於覆寫了 Son.prototype,於是 Parent 的屬性與方法都進了 Son 的原型鏈,new Son() 造出的物件自然都能取用,繼承效果達到了。

但這會帶來一個副作用:當父物件含有引用類型的屬性時,所有子物件其實共用同一份資料,改一個會影響全部。

function Parent() {
  this.name = '123';
  this.fruits = ['apple'];
}
Parent.prototype.getName = function () { return this.name; };

function Son() { this.age = 20; }
Son.prototype = new Parent();
Son.prototype.getAge = function () { return this.age; };

var son = new Son();
var son1 = new Son();

son.fruits.push('pear');
console.log(son.fruits);    // ["apple", "pear"]
console.log(son1.fruits);   // ["apple", "pear"]  ← 被連帶影響了

S2:用「對象冒充」讓每個子物件擁有自己的副本

解法是讓每個子物件在建立時,都執行一次父類建構器,取得一份屬性副本。這樣修改時改的是副本,不會外溢到其他子物件。

function Parent() {
  this.name = '123';
  this.fruits = ['apple'];
}
Parent.prototype.getName = function () { return this.name; };

function Son() {
  Parent.call(this);      // 關鍵:借用父類建構器
  this.age = 20;
}
Son.prototype = new Parent();
Son.prototype.getAge = function () { return this.age; };

var son = new Son();
var son1 = new Son();

son.fruits.push('pear');
console.log(son.fruits);    // ["apple", "pear"]
console.log(son1.fruits);   // ["apple"]  ← 互不干擾

Parent.call(this) 讓 new Son() 時的 this(即新造出的 Son 物件)冒充成 Parent 裡的上下文,因此拿到了父物件屬性與方法的副本。

但問題還沒結束:因為仍然寫著 Son.prototype = new Parent(),我們其實得到了兩份實例屬性——一份在原型上,一份在副本裡。而拿到副本之後,我們真正需要的只是父物件原型上的方法(例如 getName),實例屬性那份是多餘的。

S3:用 constructor 去掉多餘的那一份

做法是把 Parent.prototype 重新「清空」成一個不含實例屬性的物件,作為子類原型,再把 constructor 指回子建構器。

function Parent() {
  this.name = '123';
  this.fruits = ['apple'];
}
Parent.prototype.getName = function () { return this.name; };

function Son() {
  Parent.call(this);
  this.age = 20;
}

function Extend(Parent, Son) {
  var proto = new Object(Parent.prototype);   // 只承接原型,不執行建構器
  proto.constructor = Son;                    // 修正 constructor 指向
  Son.prototype = proto;
}

Extend(Parent, Son);

Son.prototype.getAge = function () { return this.age; };

三個階段的總結

  1. 原型鏈繼承:概念最簡單,但引用屬性會被所有子物件共用。
  2. 加上 Parent.call(this):解決了引用屬性共用問題,卻殘留了一份多餘的原型屬性。
  3. 用 constructor 重建原型:既保留方法繼承,又不執行父建構器,結構最乾淨。

這三步演進其實就是《JavaScript 高級程式設計》所說的組合繼承,也是 ES6 class 與 extends 在語法糖背後所做的事。理解它,才能理解 super() 為什麼必須在建構器第一行呼叫。

以上就是本次整理的內容,希望大家喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved