通過一個簡單的例子來闡述。
<script>
function Lecture(name,teacher){
this.name=name;
this.teacher=teacher;
}
Lecture.prototype.display=function(){
return this.teacher+"is teaching "+this.name;
}
function Schedule(lectures){
this.lectures=lectures;
}
Schedule.prototype.display=function(){
var str="";
for(var i=0;i<this.lectures.length;i++)
str+=this.lectures[i].display()+"! ";
return str;
}
var myLecture=new Lecture("Gym","Hunk Wang");
var myLecture2=new Lecture("Tom","Ducklyl");
var myArray=new Array(myLecture,myLecture2);
var mySchedule=new Schedule(myArray);
alert(mySchedule.display());
</script>
運行結果為:Hunk Wang is teaching Gym! Ducklyl is teaching Tom!
下面分析一下流程,以上建立兩個類Lecture和Schedule,
首先初始化Lecture類,調用Lecture類構造函數,接著把Lecture類的對象,作為參數傳入Schedule類,Schedule對象初始化,從而實現上述結果。
不難發現,這種方式和java是類似的。只過javascript要真正實現面象對象,還需要很多過程實現。
期待后續。