Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: ReferenceError: 'function' is not defined

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?

like image 781
user9030 Avatar asked Nov 24 '25 07:11

user9030


1 Answers

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.

like image 156
Saravana Avatar answered Nov 26 '25 22:11

Saravana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!