【问题标题】:Javascript OOP, a simple calculator that will not functionJavascript OOP,一个不会运行的简单计算器
【发布时间】:2014-06-21 17:37:30
【问题描述】:

我正在构建一个简单的计算器,以将其整合到一个简单的基于 Web 的 POS 系统中。我对 JS 没有太多经验,但我广泛使用 C、C++ 和 Java 编程。

在 firefox 调试器中,我得到一个异常 TypeError: "this.getValue is not a function。"当它在方法 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");

【问题讨论】:

    标签: javascript oop object methods


    【解决方案1】:

    在您的函数 updateDisplay 中,this 不指代您的 KeyPad 对象:它指的是 $(document),因为 您不在函数调用方式的同一范围内 .

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

    我不认为(也许我错了)在函数内部使用 $(document).ready 是一个好习惯。这应该可以简单地解决您的错误:

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

    正如 sroes 在评论中所说,您应该像这样使用 $(document).ready:

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

    【讨论】:

    • 是的,最好把var keyPad = new KeyPad("#keypad_display");放在准备好的文档里面。
    • 很高兴它对您有所帮助!您可以通过单击答案投票下的勾号将此答案标记为已接受;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多