在這個世界上,有很多物體都有基本的特徵與功能,然後再加上各自特殊的特徵與功能。例如下面的範例中,每一個人類都有基本的特徵,例如性別,年齡;然後人類又可以分類成教師,工人,音樂家等等。繼承是在規劃物件製造器時,建立物件型態的繼承性,此為靜態的繼承;如果要在物件產生實體後,增加特徵或方法,就要用 prototype。
- 程式用法:
<script type='text/javascript'>
function human(name, gender, age)
{
this.name=name;
this.gender=gender;
this.age=age;
this.get=function () { return this.name+' / '+this.gender+' / '+this.age+'歲';}
}
function teacher(name, gender, age, department)
{
this.person=human;
this.person(name, gender, age);
this.department=department;
this.list=print;
}
function print()
{
document.write( this.get()+' / '+this.department );
}
Ma=new teacher('馬英九','男',55,'法律系');
Ma.list();
</script> - 執行結果:
馬英九 / 男 / 55歲 / 法律系
- 上例中,物件型態 teacher 繼承了物件型態 human;其指令是 this.person=human;。
使用繼承自物件 Function 的方法 apply() 繼承物件:其語法是:
父物件.apply(參數0 [, 參數陣列]);
參數0 指定函式中 this 代表的物件。如果參數0 是 null 或 undefined,則 this 代表全域物件(global object)。參數0 也可以用基本型態資料,此時會轉換成相關的物件,例如 String, Number, Boolean。參數陣列是物件的參數。
apply() 很類似下述的 call(),差別在 apply() 用陣列傳遞物件的參數,call() 則用名稱組。apply() 也可以用物件 arguments 傳遞變動長度的參數組。
- 程式用法:
<script type='text/javascript'>
function worker(name, gender, age, skill)
{
this.skill=skill;
human.apply(this, arguments);
this.list=function () {
document.write( this.name+' : '+this.gender+' : '+this.age+' : '+this.skill);}
}
var Yun=new worker('袁師傅','男',50,'水電');
Yun.list();
</script> - 執行結果:
袁師傅 : 男 : 50 : 水電
使用繼承自物件 Function 的方法 call() 繼承物件:其語法是:
父物件.call(參數0 [, 參數1[, 參數2[, ...]]]);
參數0 指定函式中 this 代表的物件。如果參數0 是 null 或 undefined,則 this 代表全域物件。參數0 也可以用基本型態資料,此時會轉換成相關的物件,例如 String, Number, Boolean。參數1, 參數2 是物件的參數。
- 程式用法:
<script type='text/javascript'>
function musician(name, gender, age, instrument)
{
this.instrument=instrument;
human.call(this, name, gender, age);
this.list=function () {
document.write( this.name+' : '+this.gender+' : '+this.age+' : '+this.instrument);}
}
var Chen=new musician('陳美','女',30,'小提琴');
Chen.list();
</script> - 執行結果:
陳美 : 女 : 30 : 小提琴