Objects inside classes in OOP in JavaScript
Classes can use objects of other classes. Let's look at an example. Let's say we want to make a user with a first and last name, as well as the city in which he lives. Let's say we have the following class for the city:
class City {
constructor(name) {
this.name = name;
}
}
We will pass the name, surname and city as parameters of the constructor:
class User {
constructor(name, surn, city) {
this.name = name;
this.surn = surn;
this.city = city;
}
}
In this case, the first and last name will be strings, but the city will be an object of its own separate class:
let city = new City('luis');
let user = new User('john', 'smit', city);
Let's output the name of our user:
console.log(user.name);
Now let's display the name of the city for our user:
console.log(user.city.name);
The following class is given:
class Employee {
constructor(name, position, department) {
this.name = name;
this.position = position;
this.department = department;
}
}
Make the second and third parameters pass objects of separate classes.
Create a worker object using the class from the previous task.
Output to the console the name, position and department for the created employee.