I have a simple Plunkr app that adds two numbers together on the click of a button.
I am getting a ReferenceError: addNumber is not defined where add number is a function that is called by the 'onClick' handler.
onClick(num1, num2){
addNumber(num1, num2).then((result) => this.result = result));
}
addNumber(x, y){
return new Promise((resolve) => {
x = parseInt(x);
y = parseInt(y);
setTimeout(() => resolve(x+y), 2000)
})
}
}
However, if I add the function keyword to addNumber it works but as I understand it, with Typescript it is optional to use the function keyword.
Why is addNumber not defined when the button is clicked?
When accessing class members you have to reference them using this:
this.addNumber(num1, num2).then((result) => this.result = result));
When you add the function keyword to addNumber you are making it a local function instead of a class member thus making it accessible without the this reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With