My task is to create an object (instance of a sub-class) within a function, call a method on that object, and then return it using the following classes:
// Implement a Person class
class Person {
constructor(name = "Tom", age = 20, energy = 100) {
this.name = name;
this.age = age;
this.energy = energy;
}
sleep() {
this.energy += 10;
console.log("Energy has increased to ", this.energy);
}
doSomethinFun() {
this.energy -= 10
console.log("Energy has decreased to ", this.energy);
}
}
// Implement a Worker class
class Worker extends Person {
constructor(name, age, energy, xp = 0, hourlyWage = 10) {
super(name, age, energy);
this.xp = xp;
this.hourlyWage = hourlyWage;
}
goToWork() {
this.xp += 10
console.log("XP has been increased to ", this.xp);
}
}
All methods have been tested on a custom object instantiated from the Worker class with success. Now onto the challenge(s):
The goal: Within the intern function, instantiate a new object of the Worker class to create a new intern object with the specified characteristics:
- name: Bob
- age: 21
- energy: 110
- xp: 0
- hourlyWage: 10
Considering constraints preventing objects having the same name, I've named the object intern1 as per the predefined function name.
function intern() { var intern1 = new Worker("Bob", 21, 110, 0, 10); console.log(intern1); }
The objective: Execute the
goToWork()
method on the intern object. Thenreturn
the intern object.intern1.goToWork(); return intern();
While the return statement within the function automatically invokes the object, the execution of intern1.goToWork() fails due to a ReferenceError: intern1 is not defined... The issue seems to be related to scope but the solution eludes me. How can the goToWork() method be successfully executed on intern1?