0

我是 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>
4

1 回答 1

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();
    }

    ...
}
于 2013-03-06T20:08:26.570 回答