DIV CSS 佈局教程網

JavaScript 物件導向:六種 constructor 繼承寫法詳解
編輯:關於JavaScript     

這一節要處理的問題是:如何讓「貓」繼承「動物」。先準備兩個建構函式:

function Animal() {
  this.species = "動物";
}

function Cat(name, color) {
  this.name = name;
  this.color = color;
}

1. 建構函式綁定

最簡單的方式是用 call 或 apply,把父類的建構函式綁到子類上:

function Cat(name, color) {
  Animal.apply(this, arguments);
  this.name = name;
  this.color = color;
}
var cat1 = new Cat("大毛", "黃色");
alert(cat1.species);   // 動物

2. prototype 模式

更常見的做法是操作 prototype。若讓 Cat 的 prototype 指向一個 Animal 的實例,所有貓的實例自然就能繼承 Animal:

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛", "黃色");
alert(cat1.species);   // 動物

第一行等於完全丟棄 prototype 原來的值再重新指派。那第二行呢?

任何 prototype 物件都有一個 constructor 屬性指回它的建構函式。既然我們把 prototype 整個換掉了,新的 prototype 上就沒有 constructor,必須手動補回去,否則後續的「繼承鏈」會出錯。這一行不能省。

換句話說,只要替換了 prototype:

o.prototype = {};
o.prototype.constructor = o;

這兩行永遠成對出現。

3. 直接繼承 prototype

Animal 中不變的屬性其實都可以寫在 prototype 上,因此可以讓 Cat 跳過 Animal,直接繼承它的 prototype。

function Animal() {}
Animal.prototype.species = "動物";

Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛", "黃色");
alert(cat1.species);   // 動物

這種寫法效率較高、較省記憶體(不必建立 Animal 的實例),但缺點很嚴重:Cat.prototype 與 Animal.prototype 指向同一個物件,任何對 Cat.prototype 的修改都會直接影響 Animal.prototype。

也就是說,上面第二行實際上把 Animal.prototype 的 constructor 也改掉了:

alert(Animal.prototype.constructor);   // Cat —— 這不是我們想要的

4. 以空物件作為中介

為了解決上述污染問題,可以插入一個空建構函式當緩衝:

var F = function () {};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

F 是空的,幾乎不佔記憶體。此時修改 Cat.prototype 不會波及 Animal.prototype:

alert(Animal.prototype.constructor);   // Animal —— 正確

5. 封裝成 extend 函式

function extend(Child, Parent) {
  var F = function () {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
}

使用方式:

extend(Cat, Animal);
var cat1 = new Cat("大毛", "黃色");
alert(cat1.species);   // 動物

這正是 YUI 函式庫實作繼承的方式。最後一行 Child.uber = Parent.prototype 為子類開了一條通道,可直接呼叫父類的方法,屬於預留性質。

6. 拷貝繼承

換個思路:把父類的所有屬性與方法逐一拷貝到子類,不也達到繼承的效果嗎?

function Animal() {}
Animal.prototype.species = "動物";

function extend2(Child, Parent) {
  var p = Parent.prototype;
  var c = Child.prototype;
  for (var i in p) {
    c[i] = p[i];
  }
  c.uber = p;
}

extend2(Cat, Animal);
var cat1 = new Cat("大毛", "黃色");
alert(cat1.species);   // 動物

拷貝式繼承的弱點是:它複製的是「當下的值」,父類 prototype 之後新增的成員不會同步過來;而且用 for-in 走屬性時,記得搭配 hasOwnProperty 過濾掉原型鏈上的繼承屬性。

現代的寫法

ES6 之後,上述六種手法都有更清楚的對應語法:

class Animal {
  constructor() { this.species = "動物"; }
}

class Cat extends Animal {
  constructor(name, color) {
    super();                  // 對應第 1 種做法的建構函式綁定
    this.name = name;
    this.color = color;
  }
}

extends 底層走的其實就是第 4 種「空物件中介」的邏輯,而 super() 等同於 apply 綁定。理解這六種寫法之後,再看 class 語法就會發現它只是糖,底層機制沒有變。

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