J150 Complex Class with Modules
Master the concepts of module-based class creation and management in JavaScript using ES6 syntax.
In this exercise, you’ll work with three module files:
person.mjsenvironment.mjsapp.mjs
person.mjs
Description:
This module defines a person with properties like name and age and exposes methods to interact with the person’s attributes.
Content:
// person.mjs
export default class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getDetails() {
return `Name: ${this.name}, Age: ${this.age}`;
}
celebrateBirthday() {
this.age += 1;
return `Happy Birthday, ${this.name}! You are now ${this.age} years old.`;
}
}
environment.mjs
Description:
This module sets up an environment for the person with properties like country and city. It provides methods to get details about the environment.
Content:
// environment.mjs
export default class Environment {
constructor(country, city) {
this.country = country;
this.city = city;
}
getDetails() {
return `Country: ${this.country}, City: ${this.city}`;
}
}
app.mjs
Description:
This module is the application entry point. It will use both the Person and Environment classes to demonstrate their interaction.
Content:
// app.mjs
import Person from './person.mjs';
import Environment from './environment.mjs';
const person1 = new Person("John Doe", 25);
const env1 = new Environment("USA", "New York");
console.log(person1.getDetails()); // "Name: John Doe, Age: 25"
console.log(env1.getDetails()); // "Country: USA, City: New York"
console.log(person1.celebrateBirthday()); // "Happy Birthday, John Doe! You are now 26 years old."
Execution:
To execute the code in a modern Node.js environment, use the following command:
This command tells Node.js to run the app module with experimental support for ES6-style modules.
Through this exercise, learners can grasp the concepts of ES6 classes, modules, and how to structure their JavaScript code in a modular way. It also demonstrates how different modules can interact with each other.