3
Hello, I’m having to try to create two objects of the kind person using Factory
and in the first attempt I create the first element and the second attempt instead of creating the second element creates a new element, but with the same characteristics as the first element
Classe Pessoa
, that will be a 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);
}
using the function of factory
for raise a student and teacher
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
with a list of people[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);
console.log("\nID: "+this.pessoas[this.pessoaCriada.id].id+
"\nNome: "+this.pessoas[this.pessoaCriada.id].nome);
} else {
console.log("não pode ser vazio");
}
}
}
test in 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"); //
and I got that result
and there are no names of teachers Tom and Peter, or if it is only for one kind of person works all right and if you want create another type of person, returns the value of people who are already created
of the one
console.log(this.pessoas)
there are two indexes, Student and Teacher, now and only you go through them correctly to show the information.– Gabriel Rodrigues