Executing an object method within a function in Javascript: A step-by-step guide

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

  1. 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);
    }
    
  2. The objective: Execute the goToWork() method on the intern object. Then return 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?

Answer №1

Check out this awesome solution

function employee() {
  var employee1 = new Worker("Alice", 25, 120, 0, 12);
  employee1.startWork();
  return employee1;
}

const emp = employee();
console.log(emp);

Answer №2

intern() function does not have a return value but you still assigned it to something. If I interpreted correctly, you can modify your code like this:

function intern() {
    return new Employee("Bob", 21, 110, 0, 10);
}
let newIntern = intern();
newIntern.startWork();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to retrieve a value from a Headless-UI component?

I have integrated a Listbox component from Headless-UI in my React project. The Listbox is contained within its own React component, which I then include in a settings form. How can I extract the selected value from the Listbox component and save it to th ...

Tips on how to connect a single reducer function to trigger another dispatch action

In my React project, I'm utilizing a Redux-Toolkit (RTK) state slice that is being persisted with localStorage through the use of the redux-persist library. This is a simplified version of how it looks: const initLocations = [] const locationsPersist ...

Using Material-UI's <Autocomplete/> component and the getOptionLabel prop to handle an empty string value

Currently, I am working with material-ui autocomplete and passing an array of states to its options property. However, I have encountered an issue with the getOptionLabel method: Material-UI: The `getOptionLabel` method of Autocomplete returned undefined ...

Converting ASP.NET Razor C# code to TypeScript/JavaScript for working with SqlDateTime types

Currently, I am in the process of converting an older .cshtml view file into pure HTML + TypeScript with the help of Angular1. The focus here is not so much on Angular, but on finding equivalent functionality in TypeScript (or JavaScript) to replace some C ...

Styling dynamic elements with CSS can disrupt the overall layout

Currently, I am facing an issue with the layout of my website. I have two sub-container elements positioned side by side - a left navigation menu and a content display area on the right. These elements are populated in the Document.Ready() function, but th ...

TypeScript: does not match type error

I am new to using TypeScript with Angular 2. I am currently utilizing version 1 of Angular 2 CLI. During compilation, I encountered an error stating that "is not assignable to type Assignment[]". I have reviewed the data types and everything seems correct ...

How come my variable becomes 0 even though I assigned it a value that is not 0?

I initially set out to calculate the distance between the top of the page and the visible area that the viewer is currently at, in terms of pixels (vertically). The goal was for a function to scroll down on another page based on how far the user had scroll ...

Utilize JavaScript to trigger a div pop-up directly beneath the input field

Here is the input box code: <input type='text' size='2' name='action_qty' onmouseup='showHideChangePopUp()'> Along with the pop-up div code: <div id='div_change_qty' name='div_change_qty&ap ...

Image loading event doesn't trigger when used inside the useEffect() hook

I am encountering a problem with my React function where the console log message "Drawing image...." does not appear even though I do not see any errors reported from image.onerror. This issue arises when I fetch image data in base64 format fro ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Retrieving a value attribute from the isolated controller of a directive

I have a directive that reads and writes attributes, but I'm having trouble getting it to work as expected. The issue seems to be with the controller inside main-directive.js, which is empty, while the actual action is happening in the isolated direct ...

JavaScript function for validating CGPA or GPA fields

I am encountering issues with JavaScript validation in ASP.NET. The validation seems simple, but for some reason, it is not functioning properly. Below is the code that I have tried: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.as ...

Prevent popup form from showing again upon page refresh

I currently have a pop-up form that automatically loads when the page is first opened in the browser. Users are required to fill out the form, click submit, and then the form closes. However, if the page is refreshed, the pop-up form reappears. I would lik ...

Passing data back to Angular services

Using customparameters: CustomParameter[], I passed values from my ng-service to the html view through my ng-component. Now, I need to update these values: <ul> <li *ngFor="let customparameter of customparameters"> <label> &l ...

What is the best way to align two buttons on the same line if they are positioned outside of an Edit form

Struggling with my Blazor app on .NET Core 7 - I can't seem to get two buttons to display on the same line. The first button needs to be inside an edit form for submitting and inserting data, while the second button should be outside the edit form f ...

I'm only appending the final element to the JavaScript array

Currently, I have the following code: I'm endeavoring to create a new JSON object named dataJSON by utilizing properties from the GAJSON object. However, my issue arises when attempting to iterate over the GAJSOn object; only its last element is added ...

Automatically forward to next page when video finishes

On my website's landing page, I have a fullscreen video that plays. I attempted to use javascript's timeout function to automatically redirect users to another link once the video finishes playing. However, I encountered issues with inconsistency ...

Having trouble retrieving the Update Data value from the database through jQuery Ajax Bootstrap Model with JSON data

https://i.sstatic.net/27rsu.pngI'm facing an issue where my modal is displaying, but the alert shows [object Object]. I have four tables: stud, country_master_academic, master_city, and master_state. When I click on edit, the modal appears but the dat ...

Adjust an SVG text to fit perfectly within an SVG background rectangle

Inside this box are two SVGs: one for the text and one for the background rectangle. My goal is to make sure the text fits perfectly within the background rectangle without any stretching or overflowing. I don't want to break the text into multiple l ...

JavaScript classList.remove function experiencing inconsistencies

Take a look at this fiddle: JSFiddle The HTML code: <table class="myTable"> <tr> <th>Some text</th> <td class="align"> <span class=" someStyle">1</span>/<span class="otherStyle">15</span& ...