What's preventing access to class property in TypeScript when using asynchronous methods?

Consider the following TypeScript class:

class Greeter {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return "Hello, " + this.greeting;
  }

  thisworks(input) {
    console.log("I am " + input) ;
  }

  doesNotWork(input) {
    return "Hi " + this.greeting +". I am " + input;
  }   
}

We also have an array:

let myArray = ["Sam","Chris","Alex","Taylor"];

And a function:

let myFunction = (name) => {
  let obj = new Greeter(name);
  console.log(obj.greet());
};

We can map the array and execute the function for each value like this:

async.map(
  myArray,
  myFunction
);

Or we can map the array and execute a class method with each value as shown below:

let myInput = new Greeter("Sarah");

async.map(
  myArray,
  myInput.thisworks
);

However, attempting to map the array, passing each value to a class method, and accessing the class property at the same time results in an error. Here's the code that causes the issue:

let myInput = new Greeter("John");

async.map(
  myArray,
  myInput.doesNotWork
);

If you know why the last example fails and how to fix it, please share your insights.

The expected output from the failing example is:

Hi John. I am Sam
Hi John. I am Chris
Hi John. I am Alex
Hi John. I am Taylor

Instead, the error received is:

Uncaught TypeError: Cannot read property 'greeting' of undefined

There is a related plunk available here

Answer №1

One common issue that arises is related to lexical this.

To resolve this problem, it is important to ensure that you bind this either when the function is defined or when it is called.

Ensure Binding of this during Function Definition

class Person {
    name: string;

    constructor(name: string) {
      this.name = name;
    }

    displayInfo = (age) => {
      console.log("Hello, my name is " + this.name + ". I am " + age + " years old.");
    }

}

OR

Bind this at the Time of Function Call

let person1 = new Person("Alice");
async.forEach(
    peopleArray,
    person1.displayInfo.bind(person1)
);  

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

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

The cloned rows created with jQuery are failing to submit via the post method

Hello, I am currently working on a project in Django and could use some assistance with my JavaScript code. Specifically, I am trying to incorporate a button that adds new rows of inputs. The button does function properly as it clones the previous row usin ...

Is Jquery "resistant" to updating CSS properties?

Within my HTML document, there exists a div with the class fd-video-upload-box, which has the following style properties applied: background-color: rgb(236, 238, 239); outline: 1px dashed gray !important; Upon rendering, it displays correctly as intended ...

Regular expressions won't produce a match if the string is empty

At present, I am employing the regular expression /^[a-zA-Z.+-. ']+$/ to ascertain the validity of incoming strings. If the incoming string is devoid of content or solely comprises whitespace characters, my objective is for the code to generate an er ...

JavaScript duplicate function is malfunctioning

Check out this jsfiddle link: https://jsfiddle.net/3o38nbzs/4/ When I clone an object, I am able to move the clone but it does not respond to click events. https://jsfiddle.net/L5mg87jm/ When I clone an object in this example, the clone remains static. T ...

Choose individual characters one by one

I am having issues with selecting the day, month, and year separately to calculate the days until due. It seems like my substr function may not be working correctly. Can you help troubleshoot why this is happening? http://jsfiddle.net/infatti/XeqPT/15/ f ...

Implement an expand/collapse effect using CSS3 transitions

How can I implement a smooth expand/collapse effect? function expandCollapse(shID) { if (document.getElementById(shID)) { if (document.getElementById(shID + '-show').style.display != 'none') { document.getElem ...

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...

How can I use jQuery to determine the total count of JPG files in a directory

How can I use jQuery to count the number of jpg image files in my document? Here is the command to count the image files: $('#div').html($('img').length ); However, this counts all image files with the 'img' tag. Is there ...

How can I specifically disable the next month in MUI Datepicker?

Employing MUI version 5, how can I disable only the next month in the datepicker while keeping the others functional? ...

jQuery custom slider with advanced previous and next navigation capability for jumping multiple steps

I am currently learning jQuery and programming in general. Instead of using a pre-built plug-in, I decided to create my own image slider/cycle from scratch to keep the code concise and improve my skills. My function goes through each li item, adding a &ap ...

Retrieve the IP Address using Express and GraphQL

Seeking assistance here! I recently made the switch from using rest to gql, but encountered an issue along the way. In my previous setup with rest, I was able to retrieve the user's IP address using req.ip. However, when trying to implement this in th ...

Mapping a list of objects from my model to a JavaScript variable for populating fullcalendar events

I have been working on retrieving my fullcalendar events in an object array and then storing it in my view model to pass to JavaScript. However, I encountered an error when trying to store it in the scripts section as eventArray! My service layer code... ...

Saving an image and form data together in local storage can be accomplished by using JavaScript

Is there a way to save an image to local storage along with form data? I would like to store the form data in a database and keep the image in local storage. Any help would be greatly appreciated. Thank you! <form id="saveImageForm"><input type ...

Using jQuery to Delete a DOM Element Once the Ajax Call is Successful

I'm currently facing an issue with removing an element after a successful ajax request. Below is my ajax code snippet: verifyRequest.denyUser = function(requestId,element){ $.ajax({ url: loaderURL+'idverified/denyRequest', ...

Angular utilizes array format to store data in the $scope

I am working on an Angular test application where I am trying to retrieve data from a PHP page into my model. The response comes using the echo json_encode($arr); command in the PHP file and has the format [{"id":"1","name":"first","text":"description"}]. ...

Troubleshooting Issues with Passing Values in jQuery AJAX POST Requests

Currently, I am working on two basic PHP pages: notification.php <html> <head><title></title> <meta charset="UTF-8"> <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script src="ht ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

issue related to prototypejs event handlers and event triggering

Currently, I am in the process of learning both the prototype framework and javascript as a whole. My current task involves refactoring some existing code to generate HTML from data within a class by utilizing an event listener. Despite my efforts, I am en ...

Executing the same function on both mouse click and key press with HTML and JavaScript

I need help figuring out how to call the same JavaScript function whether a user clicks a mouse or presses the enter key. Here is the code I have in my HTML file, but it doesn't seem to be working. Can anyone advise on how to fix this issue? <div ...