JSFiddle - React, Tailwind, and code Playground
JavaScript
// Classe Pessoa, que será uma super classe
function Pessoa(id, nome) {
this.id = id;
this.nome = nome;
}
// Classe Aluno extends Pessoa
function Aluno(id, nome) {
Pessoa.call(this, id, nome);
}
// Classe Professor extends Pessoa
function Professor(id, nome) {
Pessoa.call(this, id, nome);
}
// utilizando a função de factory para criar aluno e professor
function Factory() {
var idAluno = 0;
var idProfessor = 0;
this.criarPessoa = function(tipo, nome) {
var pessoa = new Pessoa();
switch (tipo) {
case "1":
pessoa = new Aluno(idAluno++, nome);
break;
case "2":
pessoa = new Professor(idProfessor++, nome);
break;
}
return pessoa;
}
}
// Classe Escola com uma lista de pessoas[alunos e professores]
function Escola(id) {
this.pessoas = [];
this.factory = new Factory();
this.pessoaCriada = null;
this.criarProfessorOuAluno = function(tipo, nome) {
if (tipo !== null) {
this.pessoaCriada = this.factory.criarPessoa(tipo, nome);
this.pessoas.push(this.pessoaCriada);
var ultimo = this.pessoas.length - 1;
console.log(
"\nID: " + this.pessoas[ultimo].id +
" Nome: " + this.pessoas[ultimo].nome
);
} else {
console.log("não pode ser vazio");
}
}
}
// teste no cmd, node app.js
var escola = new Escola(1);
escola.criarProfessorOuAluno("1", "Jonh"); //
escola.criarProfessorOuAluno("1", "Bob"); //
escola.criarProfessorOuAluno("1", "Jerry"); //
escola.criarProfessorOuAluno("2", "Tom"); //
escola.criarProfessorOuAluno("2", "Peter"); //
console.log(escola.pessoas)