⊗jsOpBsCOM 23 of 60 menu

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:

class 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:

class UsersCollection { }

We will store objects with users as an array in a private property:

class UsersCollection { #users; constructor() { this.#users = []; } }

Let's make a method for adding a new user to the array:

class 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:

class 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:

let uc = new UsersCollection;

Now let's add some users to our collection:

uc.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:

uc.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.

hirocsmsuzl