3
04/11/2024 6:36 f m
Ämnesstart
Extend the Person and Teacher from the previous task and add a class Student inheriting from Person. Add toString() functions to all classes, the formats should be as follows:
- Person - returns "Person (name: {name}, email: {email})"
- Student - returns "Student (name: {name}, email: {email}, course: {course})"
- Teacher - returns "Teacher (name: {name}, email:{email}, subject:{subject})"
Try to reuse code by using the toString function of the base class.
Input:
There will be no input.
Output:
Your function should return an object containing the classes Person, Teacher and Student.
Example:
function toStringExtension() {
//TODO
return {
Person,
Teacher,
Student
}
}
1 Svar
2
04/11/2024 6:37 f m
My solution:
class Person {
constructor(name, email) {
this.name = name;
this.email = email;
}
toString() {
let className = this.constructor.name;
return `${className} (name: ${this.name}, email: ${this.email})`;
}
}
class Teacher extends Person {
constructor(teacherName, teacherEmail, subject) {
super(teacherName, teacherEmail);
this.subject = subject;
}
toString() {
let base = super.toString().slice(0, -1);
return `${base}, subject: ${this.subject})`;
}
}
class Student extends Person {
constructor(studentName, studentEmail, course) {
super(studentName, studentEmail);
this.course = course;
}
toString() {
let base = super.toString().slice(0, -1);
return `${base}, course: ${this.course})`;
}
}
let person = new Person("Maria", "maria@yahoo.bg");
let teacher = new Teacher("Ivan", "ivan@ivan.bg", "history");
let student = new Student("Pesho", "pesho@gmail.com", "Math");
console.log(person.toString());
console.log(teacher.toString());
console.log(student.toString());
/*console.log(Object.getPrototypeOf(teacher) === Teacher.prototype);
console.log(Teacher.prototype.toString);
Person.prototype.age = 21;
console.log(teacher.age);
console.log(person.age);
console.log(student.age);*/
