In: Computer Science
At the question 3 without using inheritance, how can I access to the both constructors, Student & Course with only one prototype method displayStudents to print out all of the both properties?
The JavaScript code defines a constructor function for a Student class.
given:
function Student(name, gpa) {
this.name = name;
this.gpa = gpa;}
//=======Student.js=====================
class Student{
constructor(name,GPA){
this.name=name;
this.GPA=GPA;
}
getName(){
return this.name;
}
getGPA(){
return this.GPA;
}
setName(name){
this.name=name;
}
setGPA(GPA){
this.GPA=GPA;
}
}
//_____________________
class Course{
constructor(title){
this.title=title;
this.total=0;
this.StudentArray={};
}
getTitle(){
return this.title;
}
addStudent(stud){
this.StudentArray[this.total]=stud;
this.total=this.total+1;
}
displayStudents(){
var i;
console.log(this.title);
console.log("_____________")
for(i=0;i<this.total;i++){
console.log(this.StudentArray[i].getName());
console.log(this.StudentArray[i].getGPA())
console.log("--------------")
}
console.log("_____________")
}
}
//_________________________
let C1=new Course("Java");
let s1=new Student("Tom",6.7);
let s2=new Student("Alice",8.7);
let s3=new Student("Ronnie",9.0);
C1.addStudent(s1);
C1.addStudent(s2);
C1.addStudent(s3);
C1.displayStudents();
let C2=new Course("Algorithm");
let s4=new Student("Mourice",6.88);
let s5=new Student("Anita",7.7);
let s6=new Student("Alite",9.6);
C2.addStudent(s4);
C2.addStudent(s5);
C2.addStudent(s6);
C2.displayStudents();
//===========end of Student.js==================
//output
C:\Program Files\nodejs\node.exe Student.js
Java
_____________
Tom
6.7
--------------
Alice
8.7
--------------
Ronnie
9
--------------
_____________
Algorithm
_____________
Mourice
6.88
--------------
Anita
7.7
--------------
Alite
9.6
--------------
_____________