博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

面向对象开发2

Posted on 2017-01-19 20:34  程序员入门到放弃  阅读(85)  评论(0编辑  收藏  举报
<script type="text/javascript"> 
/* 
示例用一个对象组合表示学校中的课程 
'Lecture'类 
用name和teacher作为参数 
*/ 
function Lecture(name,teacher){ 
this.name=name; 
this.teacher=teacher; 
} 
//'Lecture'类的一个方法,用于生成一条信息 
Lecture.prototype.display=function(){ 
return this.name + " 是教 "+this.teacher +" 的。" ; 
} 
//下面用new来构造一个新的函数,然后调用display方法 
var L = new Lecture("李老师","英语"); 
var L_msg = L.display(); 
//alert(L_msg); 
//新定义一个'AllLecture'类 
//用'lec'作为参数,lec是一个数组 
function AllLecture( lec ){ 
this.lec = lec; 
} 
//'AllLecture'类的一个方法,用于生成所有的课程信息 
//需要循环输出'lec' 
AllLecture.prototype.display=function(){ 
var str = ""; 
for(var i=0;i<this.lec.length;i++){ 
str += this.lec[i] + "\n"; 
} 
return str; 
} 
//下面使用new来够造一个新的函数,用于生成所有的信息 
//函数的参数是数组。 
//使用'Lecture'类来生成数组的值。 
var B = new AllLecture( [ new Lecture("李老师","英语").display() , new Lecture("张老师","数学").display() , new Lecture("刘老师","物理").display() ] ); 
var B_str = B.display(); 
alert(B_str); 
</script>