//父構造函數
function Parent(name){
this.name=name || 'ling';
}
//向該原型添加功能
Parent.prototype.say=function(){
return this.name;
}
//空白的子構造函數
function Child(name){};
//繼承開始
inherit(Child,Parent);
注:inherit()函數並非由編程語言提供,必須自己實現
#·1默認模式(prototype)
function inherit(C,P){
C.prototype=new P();
}
缺點:它同時繼承了兩個對象的屬性,在絕大多數時候,並不需要這些自身屬性,因爲他很可能是指向一個特定的實例,而不是複用。
如:
var s= new Child('zhang');
s.say(); //輸出‘ling’ 而不是’zhang‘
#·2借用構造函數(apply())
function Child(a,b,c,d){
Parent.apply(this,arguments);
}
#·3借用和設置原型(#1+#2)
function Child(a,b,c,d){
Parent.apply(this,arguments);
}
Child.prototype=new Parent();優點:運行後的結果對象能獲得父對象本身的成員副本,同時子對象也能夠將任意參數傳遞到父構造函數。
#·4共享原型
function inherit (C,P){
C.prototype=P.prototype;
}
這種模式能夠向你提供簡短而迅速的原型鏈查詢,因爲所有對象共享了同一個原型。但:如果在繼承鏈下方的某處存在一個子對象修改了原型,它將影響到所有的父對象。
#·5臨時構造函數
function inherit(C,P){
var F=function(){};
F.prototype=P.prototype;
C.prototype=new F();
}