【发布时间】:2016-11-01 13:45:37
【问题描述】:
我正在尝试创建一个简单的 JavaScript 计算器。但是,当我运行我的代码并对三个字段(值框或符号)中的任何一个进行更改时,我会收到一条错误提示
this.calculate 不是函数
错误出现在 this.calculate 下,取决于您是否更改了数值或公式符号。
我已经阅读了闭包、回调和“this”关键字,我相信问题在于我如何调用我的原型函数。有人能帮忙解释一下我在代码中哪里出错以及如何解决吗?
这里是 JavaScript
var Formula=function() {
this.value1 = null;
this.value2 = null;
this.sign = null;
this.result = null;
};
Formula.prototype.calculate = function() {
switch (this.sign) {
case '+':
this.result = this.value1 + this.value2;
break;
case '-':
this.result = this.value1 - this.value2;
break;
case '/':
this.result = this.value1 / this.value2;
break;
case '*':
this.result = this.value1 * this.value2;
break;
default:
break;
}
document.querySelector('#result').innerHTML = this.result;
};
Formula.prototype.updateValue = function(event) {
if (event.currentTarget.id === '#value1')
this.value1 = parseFloat( event.currentTarget.value );
else this.value2 = parseFloat( event.currentTarget.value );
this.calculate();
};
Formula.prototype.updateSign = function(event) {
this.sign = event.currentTarget.value;
this.calculate();
};
document.addEventListener('DOMContentLoaded', function () {
(function() {
var equation = new Formula();
document.querySelector('#sign').addEventListener('change', equation.updateSign);
var values = document.querySelectorAll('.value');
for (var i = 0, numValues = values.length; i < numValues; i++) {
values[i].addEventListener('change', equation.updateValue);
}
})();
});
这里是 HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="calcJS.js"></script>
</head>
<body>
<input type="number" class="value" id="value1"/>
<select id="sign">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" class="value" id="value2"/>
=
<span id="result"/>
</body>
</html>
【问题讨论】:
-
您好,在您获得帮助后,请不要破坏您的帖子。这就像在树下避难后砍倒一棵树。请允许其他未来的用户从知识中获益。回答者会付出很多努力。不要浪费他们宝贵的时间。
-
对不起,我试图重做代码并进行更改并提出不同的问题,而不是发一个完整的其他帖子。
-
@sota7green 也不要这样做 xD 如果您还有其他问题,再问一个问题,不要编辑当前问题。
标签: javascript callback closures this