Manipulating Objects in Classes in OOP in JavaScript
Classes can accept objects of other classes as method parameters and manipulate these objects. Let's look at an example. Let's say we have the following class:
javascriptclass User {
#name;
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
Let's say we decide to make a class that will manipulate a set of objects with users:
javascriptclass UsersCollection {
}
We will store objects with users as an array in a private property:
javascriptclass UsersCollection {
#users;
constructor() {
this.#users = [];
}
}
Let's make a method for adding a new user to the array:
javascriptclass UsersCollection {
#users;
constructor() {
this.#users = [];
}
add(user) {
this.#users.push(user);
}
}
Now let's make a method that will output the names of all users to the console:
javascriptclass UsersCollection {
#users;
constructor() {
this.#users = [];
}
add(user) {
this.#users.push(user);
}
show() {
for (let user of this.#users) {
console.log(user.getName());
}
}
}
Let's take a look at how our class works. First, let's create an object:
javascriptlet uc = new UsersCollection;
Now let's add some users to our collection:
javascriptuc.add(new User('john'));
uc.add(new User('eric'));
uc.add(new User('kyle'));
Now let's call a method that will output the names of all users to the console:
javascriptuc.show();
Make a class EmployeesCollection that will contain an array of employees.
Make a method in this class to add a new worker.
Make a method in this class to display all workers.
Create a method in this class to calculate the total salary of all employees.
Make a method in this class to calculate the average salary of all employees.