我是JavaScript的新手,我知道我的代码很奇怪,我该如何解决这个问题?另外,如何在函数内调用函数?我想将所有值转换为数字或浮点数并调用解决方案。
<script type="text/javascript">
function Math(){
var firstNumber = document.getElementById("firstnumber");
var secondNumber = document.getElementById("secondnumber");
this.add = function(){
var fN = Number( firstNumber.value );
var sN = Number( secondNumber.value );
return ( fN + sN );
}
this.sub = function(){
var fN = Number( firstNumber.value );
var sN = Number( secondNumber.value );
return ( fN - sN );
}
this.div = function(){
var fN = Number( firstNumber.value );
var sN = Number( secondNumber.value );
return ( fN - sN );
}
this.mul = function(){
var fN = Number( firstNumber.value );
var sN = Number( secondNumber.value );
return ( fN * sN );
}
}
var myNewMath = new Math();
</script>
答案 0 :(得分:1)
对于初学者来说代码不是太,如果有点重复。
为了使事情变得简单,我可能会做这样的事情以避免重复调用Number(element.value)
:
function Calculator() { // NB: not "Math" - that's a standard object
var firstNumber = document.getElementById("firstnumber");
var secondNumber = document.getElementById("secondnumber");
function op1() {
return Number(firstNumber.value);
}
function op2() {
return Number(secondNumber.value);
}
this.add = function() {
return op1() + op2();
}
this.sub = function() {
return op1() - op2();
}
...
}