0

Please see my code below.

class User {
  
  constructor(name, email) {
    this.name = name;
    this.email = email;
   
  }
  
  addUser() {
    users.push(this.name, this.email)
  }
  
}

const userOne = new User ('John', '[email protected]');
const userTwo = new User ("Alan", "[email protected]");

let users = [];

userOne.addUser();
userTwo.addUser();

After method addUser i have array with names and emails but i would like to have an array with objects as below

users = [
{ name: 'John', email: '[email protected]' }
{ name: 'Alan', email: '[email protected]' }
]

How my method addUser should looks in my prototype and if variable users is in correct place or can be store somewhere in Class? Thanks in advance

3
  • Why not just writing users = [userOne, userTwo];? Commented Mar 27, 2021 at 16:23
  • Thanks, but I was looking for method to my prototype as my template Commented Mar 27, 2021 at 17:03
  • It is an antipattern to have a method that mutates a global variable. It goes against the OOP principles. Commented Mar 27, 2021 at 18:16

2 Answers 2

1

You're pushing the object properties one after the other, rather than as an object together.

Try this for your addUser method:

addUser() {
  users.push({name: this.name, email: this.email})
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. This is what I was looking for
0

You just need to push each proprieties

users.push({name: this.name, email: this.email})

If you want to do this automatically you can use:

users.push(Object.assign({}, this))

Or you cloud just pass the whole object:

users.push(this)

Anyhow, I would suggest not to use users globally.

1 Comment

Thanks for your help, both metods are works fine for me !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.