DIV CSS 佈局教程網

JavaScript 繼承實戰:借用構造函數與組合式繼承
編輯:關於JavaScript     

原型鏈很好用,但它有一個結構性缺陷:原型上的屬性是被所有實例共享的,一旦那個屬性是陣列或物件這類引用型別,其中一個實例改動,其他實例就跟著變。下面要談的借用構造函數,正是為了拆掉這顆地雷而出現。

借用構造函數(constructor stealing)

又稱偽造物件或經典繼承。基本想法很單純:在子類的構造函數裡面呼叫超類型的構造函數。透過 apply() 或 call(),就能讓超類型的初始化程式碼在新建立之子物件上執行。

 function SuperType(){ this.colors = ["red", "blue", "green"]; } function SubType(){ //繼承了 SuperType SuperType.apply(this); } var instance1 = new SubType(); instance1.colors.push("black"); alert(instance1.colors); //red,blue,green,black var instance2 = new SubType(); alert(instance2.colors); //red,blue,green

關鍵在 SuperType.apply(this) 這一行:this 指向即將生成的 SubType 實例,因此 this.colors 變成每個實例各自擁有的屬性。instance1 塞進 black 之後,instance2 完全不受影響。

可以傳參數

這是借用構造函數相對原型鏈的一大優勢。

 function SuperType(name){ this.name = name; } function SubType(){ SuperType.call(this, "Bob"); this.age = 18; } var instance1 = new SubType(); alert(instance1.age); //18 alert(instance1.name); //Bob

它的限制

所有方法都定義在構造函數裡,每建立一個實例就重新產生一份函數,函數復用無從談起。同時,定義在超類型原型上的方法,對子類型來說是完全看不到的。

組合繼承(combination inheritance)

也叫偽經典繼承,做法是把原型鏈與借用構造函數兩種技術拼在一起,各取所長:

用原型鏈繼承原型上的屬性與方法;用借用構造函數繼承實例自己的屬性。

 function SuperType(name){ this.name = name; this.colors = ["red", "blue", "green"]; } SuperType.prototype.sayName = function(){ alert(this.name); } function SubType(name, age){ //繼承屬性 SuperType.call(this, name); this.age = age; } //繼承方法 SubType.prototype = new SuperType(); SubType.prototype.sayAge = function(){ alert(this.age); } var instance1 = new SubType("Bob", 22); instance1.colors.push("black"); alert(instance1.colors); //red,blue,green,black instance1.sayName(); //Bob instance1.sayAge(); //22 var instance2 = new SubType("Alice", 21); alert(instance2.colors); //red,blue,green instance2.sayName(); //Alice instance2.sayAge(); //21

拆解這段程式碼:SuperType 定義了 name 與 colors 兩個實例屬性,並在原型上掛了 sayName()。SubType 一邊用 call 把 name 傳進去完成屬性繼承並定義自己的 age,另一邊把 SuperType 的實例指派給自己的 prototype 完成方法繼承,最後在這個新原型上補了 sayAge()。

結果是 instance1 與 instance2 各自擁有獨立的 colors 陣列,同時共享同一份 sayName 與 sayAge 函數——兩種繼承方式各自的優點都拿到了。

它仍有代價

組合繼承並非終點。SubType.prototype = new SuperType() 這一步會多跑一次超類型構造函數,實屬浪費;更麻煩的是,constructor 指標會因此被改寫,需要手動補回 SubType.prototype.constructor = SubType。ES6 的 class 與 extends 語法糖,正是為了把這一切收斂成乾淨的寫法。

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