lundi 21 décembre 2020

Random method returns same object

I'm learning javascript and made an exercise to practise using objects. I've got an generateRandomPerson() function to take person-object, give it random properties then return the object. When I call the method generateRandomPerson().getInfo() twice it prints two different objects. But when I create two different variables and assign them to generateRandomPerson() the variables contains identical objects. I don't understand why this is happening?

Object

person = {
  details :{
    name : null,
    surName : null,
    age : null,
    accBalance : null
  },
  personalCar : null,
  setName(givenName){
    this.details.name = givenName;
  },
  setSurName(givenName){
    this.details.surName = givenName;
  },
  setAge(givenAge){
    this.details.age = givenAge;
  },
  setAccBalance(givenBalance){
    this.details.accBalance = givenBalance;
  },
  setPersonalCar(givenCar){
    this.personalCar = givenCar;
  },
  getInfo(){
    for(let detail in this.details){
      console.log(`${detail}: ${this.details[detail]}`);
    }
  },
  getHTML(){
    let mainContainer = document.createElement('div');
    for(let detail in this.details){
      let info = document.createElement('p');
      info.appendChild(document.createTextNode(`${detail}: ${this.details[detail]}`));
      mainContainer.appendChild(info);
    }
    return mainContainer;
  }
}

generateRandomPerson()

generateRandomPerson = () =>{
  let genPer = person;
  genPer.setName(names[Math.floor(Math.random() * names.length)]);
  genPer.setSurName(surNames[Math.floor(Math.random() * surNames.length)]);
  genPer.setAge(Math.floor(Math.random() * 62) + 18);
  genPer.setAccBalance(Math.floor(Math.random() * 9000)+1000);
  genPer.setPersonalCar(generateRandomCar());
  return genPer;
}

Why does the variables contain the same object but calling generateRandomPerson().getInfo(); twice generate two different objects?

let man0 = generateRandomPerson();
let man1 = generateRandomPerson();

man0.getInfo(); //Loggs a person
man1.getInfo(); //Loggs the same person

generateRandomPerson().getInfo(); //Loggs a person
generateRandomPerson().getInfo(); //Loggs a new person



Aucun commentaire:

Enregistrer un commentaire