gpt4 book ai didi

Javascript OOP,一个不会运行的简单计算器

转载 作者:行者123 更新时间:2023-11-30 17:29:25 25 4
gpt4 key购买 nike

我正在构建一个简单的计算器,以将其整合到一个简单的基于 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");

最佳答案

在您的函数 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");
});

关于Javascript OOP,一个不会运行的简单计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23472126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com