3

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

what is the difference ?
Didn't see yours. Mine explains why adding function before it works.
I chose this one as the answer because although the solution is the same as @Sajeetharan's, you explain what the problem was
2

Use this for existing class self functions

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.