Your User
class should only be dealing with things about that user, not about how you store it in a list. You are also referring to a variable outside your class, so you are locked to this, which makes it less reusable, which is one of points of classes in the first place. So get rid of addUser
and getUserListAboveTwenty
from your class.
You don't need to pass the user to your functions, you can access it with this
, like you've done in the constructor. You can also make your addAge
function more general by adding age based on a parameter.
addAge(age){ this.age += age; }
If you just need to store your users in a list, an array is just fine. But if you want more functionality you could make a UserList class.
class UserList { constructor(users = []) { this.list = users; } addUser(user) { this.list.push(user); } getUserById(id) { return this.list.find(user => user.id == id); } getUsersAboveTwenty() { return new UserList(this.list.filter(user => user.age > 20)); } }
I've added an additional function to return a user from an id. I also made getUsersAboveTwenty
return a new UserList. You can add more if you need it (A way to add more users at the same time would be useful). Full code:
class User { constructor(name, id, age) { this.name = name; this.id = id; this.age = age; } addAge(age){ this.age += age; } } class UserList { constructor(users = []) { this.list = users; } addUser(user) { this.list.push(user); } getUserById(id) { return this.list.find(user => user.id == id); } getUsersAboveTwenty() { return new UserList(this.list.filter(user => user.age > 20)); } } let userList = new UserList(); userList.addUser(new User('user1',1,12)); userList.addUser(new User('user2',2,18)); userList.addUser(new User('user3',3,21)); userList.addUser(new User('user4',4,22)); userList.getUserById(1).addAge(3); userList.getUsersAboveTwenty(); userList.getUserById(1).addAge(3);