2017-10-29 42 views
0

我試圖做一個加法問題產生構造,但是當我跑我的代碼,我得到「未捕獲的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? –

回答

4

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,並按預期工作。謝謝你的幫助! –

相關問題