DIV CSS 佈局教程網

JavaScript 繼承機制全面解析:從原型鏈到寄生組合式繼承
編輯:關於JavaScript     

JavaScript 沒有 class 這個關鍵字(ES6 之前更是如此),它是基於對象的語言。想要複用行為與數據,工程師必須借助 prototype 原型機制,或者靈活運用 call、apply 這兩個函數方法。本文把常見的繼承方案逐一梳理,並比較它們的取捨。

一、先理解原型這個「模板」

在傳統面向對象語言裡,我們用類來生產自定義對象;而在 JavaScript 中萬物皆對象,於是問題變成:如何生產自定義對象?答案就是原型。

你可以把 prototype 想像成一份模板,新實例並不是真的複製了一份內容,而是內部持有一個不可見的指針 __proto__,指向原型對象,形成一條查找鏈。訪問屬性時,若當前對象沒有,引擎就沿著這條鏈往上找,直到 Object.prototype 為止。

JavaScript 通常用「構造函數 + 原型」來模擬類的能力,而所謂的類式繼承,最終仍然是靠原型鏈落地的。

二、原型鏈繼承

核心思路非常直白:把父類型的實例賦值給子類型的 prototype,子類 therefore 就接入了父類所在的那條鏈。

<script>
  function Parent(){
    this.name = 'mike';
  }

  function Child(){
    this.age = 12;
  }
  Child.prototype = new Parent(); // 關鍵一步:形成鏈條

  var test = new Child();
  alert(test.age);
  alert(test.name);   // 得到被繼承的屬性 mike

  // 鏈條還能繼續往下延伸
  function Brother(){
    this.weight = 60;
  }
  Brother.prototype = new Child();

  var brother = new Brother();
  alert(brother.name);  // mike,同時繼承了 Parent 與 Child
  alert(brother.age);   // 12
</script>

鏈條的頂端其實是 Object——所有構造函數最終都源自它,這一環由引擎自動完成,不需要我們手動接上。

三、如何確認原型與實例的關係

有兩種常用手段:instanceof 操作符與 isPrototypeOf() 方法。

alert(brother instanceof Object); // true
alert(test instanceof Brother);   // false,test 是 brother 的超類實例
alert(brother instanceof Child);  // true
alert(brother instanceof Parent); // true

只要某個原型在鏈上出現過,它就是該鏈派生實例的原型,因此 isPrototypeOf() 也會返回 true。

術語約定:被繼承的函數稱為超類型(父類/基類),繼承別人的稱為子類型(子類/派生類)。

純原型鏈繼承有兩個明顯短板:一是引用類型屬性會被所有實例共享,改一個等於改全部;二是子類型沒辦法在創建時向超類型傳參。

四、借用構造函數(類式繼承)

為了解決引用共享與無法傳參的問題,可以在子類型內部直接調用超類型構造函數,並用 call 把 this 替換成當前實例。

<script>
  function Parent(age){
    this.name = ['mike','jack','smith'];
    this.age = age;
  }

  function Child(age){
    Parent.call(this, age);
  }

  var test = new Child(21);
  alert(test.age);   // 21
  alert(test.name);  // mike,jack,smith
  test.name.push('bill');
  alert(test.name);  // mike,jack,smith,bill —— 不影響其他實例
</script>

缺點也很清楚:方法只能在構造函數裡定義,函數復用無從談起。

五、組合繼承:原型鏈 + 借用構造函數

把兩者拼在一起,就是實戰中最常見的方案。

<script>
  function Parent(age){
    this.name = ['mike','jack','smith'];
    this.age = age;
  }
  Parent.prototype.run = function () {
    return this.name + ' are both ' + this.age;
  };

  function Child(age){
    Parent.call(this, age);   // 借用構造函數,負責實例屬性與傳參
  }
  Child.prototype = new Parent(); // 原型鏈,負責原型上的方法

  var test = new Child(21);
  alert(test.run()); // mike,jack,smith are both 21
</script>

思路是分工:原型鏈承接原型上的屬性與方法,借用構造函數承接每個實例自己的屬性。既實現了方法復用,又保證實例數據彼此隔離。

順帶一提 call 的簽名:call([thisObj[, arg1[, arg2[, ...]]]]),第一個參數是新的 this 指向,後續參數逐一列出。

六、原型式繼承

不麻煩麻煩地定義新類型,直接拿一個已有對象當原型來造新對象,這就是原型式繼承。

<script>
  function obj(o){
    function F(){}
    F.prototype = o;
    return new F();
  }

  var box = {
    name : 'trigkit4',
    arr : ['brother','sister','baba']
  };

  var b1 = obj(box);
  alert(b1.name);        // trigkit4

  b1.name = 'mike';
  alert(b1.name);        // mike,自有屬性遮蔽了原型屬性

  alert(b1.arr);         // brother,sister,baba
  b1.arr.push('parents');
  alert(b1.arr);         // brother,sister,baba,parents

  var b2 = obj(box);
  alert(b2.name);        // trigkit4
  alert(b2.arr);         // brother,sister,baba,parents —— 引用依然共享
</script>

內部做三件事:建一個臨時構造函數、把傳入對象掛為它的原型、返回一個新實例。ES5 之後的 Object.create() 就是這個思路的標準化封裝。

七、寄生式繼承

把原型式繼承與工廠模式結合,目的是把創建過程封裝起來,順便能對新對象做增強。

<script>
  function create(o){
    var f = obj(o);
    f.run = function () {
      return this.arr;   // 注意:引用仍然共享
    };
    return f;
  }
</script>

八、組合繼承的隱性成本

組合繼承雖是主流,卻有一個浪費:超類型構造函數會被調用兩次。

<script>
  function Parent(name){
    this.name = name;
    this.arr = ['哥哥','妹妹','父母'];
  }
  Parent.prototype.run = function () {
    return this.name;
  };

  function Child(name, age){
    Parent.call(this, name);  // 第二次調用
    this.age = age;
  }
  Child.prototype = new Parent(); // 第一次調用
</script>

第一次發生在為子類型原型賦值時,第二次發生在子類型構造函數內部。第一次生成的實例屬性其實隨後就被 Parent.call 覆蓋掉了,白跑一趟。

九、寄生組合式繼承

解法很巧妙:不讓 Child.prototype 指向 new Parent(),而是指向一個「只借用了 Parent.prototype」的臨時對象,這樣父類構造函數只執行一次。

<script>
  function obj(o){
    function F(){}
    F.prototype = o;
    return new F();
  }

  function inheritPrototype(subType, superType){
    var prototype = obj(superType.prototype); // 創建對象
    prototype.constructor = subType;          // 增強對象:修正 constructor 指向
    subType.prototype = prototype;
  }

  function Parent(name){
    this.name = name;
    this.arr = ['brother','sister','parents'];
  }
  Parent.prototype.run = function () {
    return this.name;
  };

  function Child(name, age){
    Parent.call(this, name);
    this.age = age;
  }
  inheritPrototype(Child, Parent); // 一行完成原型鏈接

  var test = new Child('trigkit4', 21);
  test.arr.push('nephew');
  alert(test.arr);    // 引用問題已解決
  alert(test.run());  // 方法成功共享

  var test2 = new Child('jack', 22);
  alert(test2.arr);   // brother,sister,parents —— 互不干擾
</script>

寄生組合式繼承被普遍視為引用類型繼承的最佳實踐:只共享方法、不共享引用屬性,且父類只初始化一次。

十、順手說說 call 與 apply

這兩個方法都能改變函數內 this 的指向,差別只在參數傳遞形式:call 逐一列舉,apply 接收數組。

// 定義一個全局函數
function foo() {
  console.log(this.fruit);
}

// 定義一個全局變量
var fruit = "apple";

// 自定義一個對象
var pack = {
  fruit: "orange"
};

foo.apply(window); // "apple",此時 this 等於 window
foo.apply(pack);   // "orange",此時 foo 中的 this === pack

理解 this 的指向規則,是理解借用構造函數這類技巧的前提。

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