物件導向(繼承) 借用建構函式02

2021-08-28 19:21:21 字數 1293 閱讀 8774

首先回顧一下原型鏈中引用型別值帶來的問題

function supertype() 

function subtype() {}

//繼承了 supertype

subtype.prototype = new supertype();

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,black"

使用借用建構函式可以解決這個問題。

function supertype() 

function subtype()

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"

1. 傳遞引數

可以在子型別建構函式中向超型別建構函式傳遞引數。

function supertype(name) 

function subtype()

var instance = new subtype();

alert(instance.name); //"nicholas";

alert(instance.age); //29

1)以上**中的 supertype 只接受乙個引數 name ,該引數會直接賦給乙個屬性。在 subtype 建構函式內部呼叫 supertype 建構函式時,實際上是為 subtype 的例項設定了 name 屬性。

2)為了確保supertype 建構函式不會重寫子型別的屬性,可以在呼叫超型別建構函式後,再新增應該在子型別中定義的屬性。

2. 借用建構函式的問題

借用建構函式的技術也是很少單獨使用的。方法都在建構函式中定義,因此函式復用就無從談起了。而且,在超型別的原型中定義的方法,對子型別而言也是不可見的。

借用構造函式呼叫繼承

function father name,age 這樣直接呼叫,那麼father中的this只的是 window。因為其實這樣呼叫的 window.father 李四 20 name 和age 屬性就新增到了window屬性上 father 李四 20 alert name window.name ...

借用建構函式實現繼承

在子型別建構函式的內部呼叫超型別的建構函式 function supertype function subtype var instance1 new subtype instance1.colors.push yellow console.log instance1.colors var inst...

繼承方式二 借用建構函式

function supertype function subtype var instance1 newsubtype instance1.colors.push black console.log instance1.colors red blue green black var instanc...