首页 > 代码库 > JavaScript实现计算器功能
JavaScript实现计算器功能
截图 :
cal.js
Js代码
- var Class = {} ;
- Class.calculation = function(){
- var calculation = {} ;
- calculation.result = 0 ;
- calculation.calculate = function(num1,num2){} ;
- calculation.getResult = function(){
- return this.result ;
- } ;
- return calculation ;
- } ;
- Class.add = function(){
- var add = Class.calculation() ;
- add.calculate = function(num1,num2){
- this.result = num1 + num2 ;
- } ;
- return add ;
- }
- Class.subtraction = function(){
- var subtraction = Class.calculation() ;
- subtraction.calculate = function(num1,num2){
- this.result = num1 - num2 ;
- } ;
- return subtraction ;
- }
- Class.multiply = function(){
- var multiply = Class.calculation() ;
- multiply.calculate = function(num1,num2){
- this.result = num1 * num2 ;
- } ;
- return multiply ;
- }
- Class.divide = function(){
- var divide = Class.calculation() ;
- divide.calculate = function(num1,num2){
- this.result = num1 / num2 ;
- } ;
- return divide ;
- }
- Class.calculator = function(num1,num2,op){
- var obj = null ;
- var num1 = parseInt(num1) || 0 ;
- var num2 = parseInt(num2) || 0 ;
- if("+" == op){
- obj = Class.add() ;
- }
- else if("-" == op){
- obj = Class.subtraction() ;
- }
- else if("*" == op){
- obj = Class.multiply() ;
- }
- else if("/" == op){
- if(0 == num2){
- alert("除数不能为零!") ;
- return ;
- }
- obj = Class.divide() ;
- }
- else{
- alert("无效的" + op + "操作符!") ;
- return ;
- }
- obj.calculate(num1,num2) ;
- alert("计算结果:" + obj.getResult()) ;
- }
测试 :
Html代码
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <HTML>
- <HEAD>
- <TITLE>JavaScript面向对象</TITLE>
- <script type="text/javascript" src=http://www.mamicode.com/"js-lib/cal.js"></script>
- <script type="text/javascript">
- window.onload = function(){
- document.getElementById("command").onclick = function(){
- var n1 = document.getElementById("n1").value ;
- var opera = document.getElementById("opera").value ;
- var n2 = document.getElementById("n2").value ;
- Class.calculator(n1,n2,opera) ;
- }
- } ;
- </script>
- </HEAD>
- <BODY>
- 操作数1 : <input type="text" id="n1" /></br></br>
- 操作符号 : <input size="4" type="text" id="opera" /></br></br>
- 操作数2 : <input type="text" id="n2" /></br></br>
- <input type="button" id="command" value=http://www.mamicode.com/"计算" />
- </BODY>
- </HTML>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。