我想创建一个名为 SchoolCatalog 的类,它将保存学校的集合,例如为小学、初中和高中创建一个 SchoolCatalog 实例。 (这是 Code Academy Introduction To JavaScript 中的问题之一)。但是,他们没有关于如何制作目录以容纳论坛中所有类(class)的适当指南。所以,如果有人能帮助我,我将不胜感激。
class School {
constructor(name, level, numberOfStudents) {
this._name = name
this._level = level
this._numberOfStudents = numberOfStudents
}
get name() {
return this._name
}
get level() {
return this._level
}
get numberOfStudents() {
return this._numberOfStudents
}
set numberOfStudents(studentsNumber) {
if (typeof studentNumber === 'number')
this._numberOfStudents = studentsNumber
else
console.log(`Invalid input: numberOfStudents must be set to a Number.`)
}
quickFacts() {
console.log(`${this._name} educates ${this._numberOfStudents} students at the ${this._level} school level.`)
}
static pickSubstituteTeacher(substituteTeachers) {
const randomTeacher = Math.floor(Math.random() * substituteTeachers.length)
console.log(substituteTeachers[randomTeacher])
}
}
// Primary School
class PrimarySchool extends School {
constructor(name, numberOfStudents, pickupPolicy) {
super(name, 'primary', numberOfStudents)
this._pickupPolicy = pickupPolicy
}
get pickupPolicy() {
return this._pickupPolicy
}
}
class HighSchool extends School {
constructor(name, numberOfStudents, sportsTeams) {
super(name,'high', numberOfStudents)
this._sportsTeams = sportsTeams
}
get sportsTeams() {
this._sportsTeams.forEach(team => {
console.log(team)
})
}
}
const lorraineHansbury = new PrimarySchool('Lorraine Hansbury', 514, 'Students must be picked up by a parent, guardian, or a family member over the age of 13.')
lorraineHansbury.quickFacts()
PrimarySchool.pickSubstituteTeacher(['Jamal Crawford', 'Lou Williams', 'J. R. Smith', 'James Harden', 'Jason Terry', 'Manu Ginobli'])
const alSmith = new HighSchool('Al E. Smith', 415, ['Baseball', 'Basketball', 'Volleyball', 'Track and Field'])
alSmith.sportsTeams
// My Attempt To Make Collection of Classes
/*class SchoolCatalog {
constructor(schools) {
this._schools = schools
}
get schools() {
this._schools.forEach(school => {
console.log(school)
})
}
}
const catalog = new SchoolCatalog([''])*/
最佳答案
您的实现有问题吗?
class Catalog{
constructor(){
this.schools = []
}
addSchool(school){
if(!this[school._name]){
// reference for easy access
this[school._name]=school;
}
this.schools.push(school);
}
}
如果我需要一个列表,我可以遍历并仍然可以轻松地从中获得单一学校,这就是我的做法,
也就是说,根据您的要求,这可能是完全错误的。
你的实现乍一看并没有错, 它给你一个错误吗?
关于javascript - 如何在 JavaScript 中创建一个包含其他类集合的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61494502/