0

I'm trying to make a constructor for an addition problem generator but when I run my code I get "Uncaught ReferenceError: firstNum is not defined"

function GenAddProb()
{
    this.firstNum = returnRandomInt(1,10);
    this.secondNum =  returnRandomInt(1,10);
    this.ans = firstNum+secondNum;
}

Is there something wrong with the way my constructor is written? From what I've seen in tutorials I don't have to define firstNum and secondNum as variables before I use them in the constructor.

1
  • this.ans = firstNum+secondNum; where you found firstNum and secondNum? Commented Oct 29, 2017 at 3:53

1 Answer 1

4

this.ans = firstNum+secondNum;

As it says, firstNum is not defined. Did you mean this.ans = this.firstNum + this.secondNum?

From what I've seen in tutorials I don't have to define firstNum and secondNum as variables before I use them in the constructor.

You don't need to define this, if that's what you mean. In the context of a constructor, this is the object you're constructing. But if you want to create and use local variables, you'll need to define them.

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

1 Comment

I see. So I still have to reference what object I'm using even if it's from within the constructor. Changed it to this.ans = this.firstNum + this.secondNum and it works as intended. Thanks for your help!

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.