未捕获引用错误,当我试图做一个Javascript对象

未捕获引用错误,当我试图做一个Javascript对象

问题描述:

我试图做一个加法问题产生构造,但是当我跑我的代码,我得到“未捕获的ReferenceError:未定义firstNum”未捕获引用错误,当我试图做一个Javascript对象

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

我的构造函数的写法有什么问题吗?从我在教程中看到的,在构造函数中使用它们之前,我不必将firstNum和secondNum定义为变量。

+0

'this.ans = firstNum + secondNum;'你在哪里找到firstNum和secondNum? –

this.ans = firstNum+secondNum;

正如它所说的,firstNum没有定义。你的意思是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.

你并不需要定义this,如果这是你的意思。在构造函数的上下文中,this是您正在构建的对象。但是如果你想创建和使用局部变量,你需要定义它们。

+0

我明白了。所以我仍然需要引用我使用的对象,即使它来自构造函数。将其更改为this.ans = this.firstNum + this.secondNum,并按预期工作。谢谢你的帮助! –