2014-05-05 50 views
1

我正在建立一個簡單的計算器,將其納入一個簡單的基於Web的POS系統。我對JS沒有多少經驗,但是我已經廣泛地在C,C++ & Java中編程。JavaScript OOP,一個簡單的計算器,將不會運作

在firefox調試器中,我得到一個TypeError異常:「this.getValue不是函數。」當它在方法updateDisplay()中調用時。

它在JS中不支持這種結構嗎?在對象的方法中調用對象方法?

http://jsfiddle.net/uPaLS/33/

function KeyPad(divReference) { 
    this.divDisplay = divReference; 
    this.value = "0"; 
    this.comma = false; 
} 
KeyPad.prototype.getValue = function() { 
    return parseFloat(this.value); 
}; 
KeyPad.prototype.updateDisplay = function() { 
    $(document).ready(function() { 
     $(this.divDisplay).text(this.getValue()); 
    }); 
}; 
KeyPad.prototype.keyPressed = function (valueString) { 
    if (valueString == '.' && this.comma === true) { 
     return; 
    } 
    this.value = this.value + valueString; 
    if (valueString == '.') { 
     this.comma = true; 
    } 
    this.updateDisplay(); 
}; 
KeyPad.prototype.reset = function() { 
    this.value = "0"; 
    this.comma = false; 
    this.updateDisplay(); 
}; 


var keyPad = new KeyPad("#keypad_display"); 

回答

2

在你的函數updateDisplay,this並不是指按鍵板的對象:指的$(document),因爲 您如何功能的相同範圍 不是叫做。

KeyPad.prototype.updateDisplay = function() { 
    //'this' is Keypad 
    $(document).ready(function() { 
     //'this' is $(document) 
     $(this.divDisplay).text(this.getValue()); 
    }); 
}; 

我不認爲(也許我是錯的),使用$(文件)。就緒這裏,一個函數內部,是一個很好的做法。這應該簡單地固定你的錯誤:

KeyPad.prototype.updateDisplay = function() { 
     $(this.divDisplay).text(this.getValue()); 
}; 

由於sroes的評論,你應該使用$(文件)。就緒這樣說:

$(document).ready(function() { 
    var keyPad = new KeyPad("#keypad_display"); 
}); 
+2

呀,這將是更好地把'變種keyPad =新的KeyPad(「#keypad_display」);'文件準備就緒。 – sroes

+0

謝謝你的幫助。有用! – Phoz

+0

很高興幫助你!您可以通過點擊答案投票中的勾號將此答案標記爲已接受;) – Getz