user9030
user9030

Reputation: 139

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?

Upvotes: 3

Views: 13848

Answers (2)

Saravana
Saravana

Reputation: 40712

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.

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222657

Use this for existing class self functions

onClick(num1, num2) {
  this.addNumber(num1, num2).then((result) => this.result = result));
}

Upvotes: 2

Related Questions