截图 :
cal.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()) ;
- }
测试 :
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <HTML>
- <HEAD>
- <TITLE>JavaScript面向对象</TITLE>
- <script type="text/javascript" src="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="计算" />
- </BODY>
- </HTML>