2

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

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

2

You have a variable that isn't apart of the class, it is getting reset every time you create a new instance of person. Instead make it a property of the class person, so it looks like this:

class Person {

  constructor(name, age){
    this.p = {
      name, age
    }
  }

  greeting(){
    console.log("Hi, I'm ", this.p);
  }
}

You could also split them into their own variables:

class Person {

  constructor(name, age){
    this.name = name;
    this.age = age;
  }

  greeting(){
    console.log("Hi, I'm ", this.name, this.age);
  }
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338