我想在Javascript中实现has-a关系, 这里有Department对象,Department有多个学生,因此在Department中引用了一系列Student对象,
这是代码,
(function(){
alert(" Hi !!!!! ");
var engBranch = {
compEng : "Bachelor of Engineering in Computer Science",
mechEng : "Bachelor of Engineering in Mechanical",
cvlEng : "Bachelor of Engineering in Civil",
prodEng : "Bachelor of Engineering in Production",
elecEng : "Bachelor of Engineering in Electrical",
extcEng : "Bachelor of Engineering in Electronics and Telecomminication"
};
var StudentIdGenerator = function(studentId,dept){
var _studentId = "";
if(dept == engBranch.compEng){
_studentId = "CS"+studentId;
}else if(dept == engBranch.mechEng){
_studentId = "M"+studentId;
}else if(dept == engBranch.cvlEng){
_studentId = "CVL"+studentId;
}else if(dept == engBranch.prodEng){
_studentId = "P"+studentId;
}else if(dept == engBranch.elecEng){
_studentId = "ELC"+studentId;
}else if(dept == engBranch.extcEng){
_studentId = "EXTC"+studentId;
}
return _studentId;
}
var Student = function(studentName,studentId,department){
var _studentId = StudentIdGenerator(studentId,department);
return function(){
this.getStudentName = function(){
return studentName;
}
this.getStudentId = function (){
return _studentId;
}
this.display = function(){
return "The Student Name is "+this.getStudentName()+" having ID "+this.getStudentId();
}
};
}
Student.prototype.display = function(){
return "The Student Name is "+this.getStudentName()+" having ID "+this.getStudentId();
}
var Department = function(deptName,deptId){
this.getDeptName = function(){
return deptName;
}
this.getDeptId = function(){
return deptId;
}
this.setStudents = function(students){
this.students = students;
}
this.getStudents = function(){
return this.students;
}
}
Department.prototype.display = function(){
var str = "This is department, "+this.getDeptName()+", Students Belonging to this department are \n";
for(var x=0; x < this.getStudents().length;x++){
str += this.getStudents()[x].display()+"\n";
}
return str;
}
var department = new Department(engBranch.cvlEng,"CMP007");
var studentArray = [
new (Student("Jack Nicholson","0021",department.getDeptName()))(),
new (Student("Heidi Klum","0043",department.getDeptName()))(),
new (Student("Stephen Halkwins","0345",department.getDeptName()))(),
new (Student("Jay Leno","1045",department.getDeptName()))(),
new (Student("Tomy Lee Johnes","3475",department.getDeptName()))(),
new (Student("Oliver Jackson","7345",department.getDeptName()))()
];
department.setStudents(studentArray);
alert(department.display());
})();
在上面的代码中,对象“engBranch”包含工程课程中可用的所有流。
有一个单独的函数StudentIdGenerator(),其职责是根据学生所属的部门创建一个StudentId。
Student Constuctor函数本身返回一个新函数,请看看Student函数返回的内容。
学生的原型显示功能完全没有要求,请忽略它,
部门构造函数,
在Department原型链中显示功能,
所以,我的问题是,我的例子是一个适当的 - 一对多关系的实现。
我可以对以下代码执行新的或额外的操作。
等待你的回复