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