I'm get stuck filling up an array of class instances. To make a long story very short I create a class person (with attributes and functions on it) and I'd like to fill up an array of person's instances just pushing in the array "new" instance of the person's class. As result the array is filled up with many elements pointing to the last instance created.
Here a simplified example code. https://repl.it/@expovin/ArrayOfClassInstances
let p={
name:"",
age:""
}
class Person {
constructor(name, age){
p.name=name;
p.age=age;
}
greeting(){
console.log("Hi, I'm ",p);
}
gatOler(){
p.age++;
}
}
module.exports = Person;
It is used like this:
let person = require("./Person");
var crowd = [];
console.log("Let's create an instance of Person in the crowd array");
crowd.push(new person("Vinc", 40));
console.log("Instance a is greeting");
crowd[0].greeting();
console.log("Let's add a new instance of Person as next element in the same array");
crowd.push(new person("Jack", 50));
crowd[1].greeting();
console.log("I expect to have two different people in the array");
crowd.forEach( p => p.greeting());
Where is my fault?
Thanks in advance for your help