JavaScript編寫計算器的發展史

xbhog發表於2021-07-11

JavaScript編寫計算器的發展史:

編寫一個普通的四則運算:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>四則運算</title>
</head>
<body>
    <input type="text" id="x"/>
    <select name="" id="opt">
        <option value="0">+</option>
        <option value="1">-</option>
        <option value="2">*</option>
        <option value="3">/</option>
    </select>
    <input type="text" id="y"/>
    <button id="cal" onclick= "fn()">=</button>
    <input type="text" id="result"/>
    <script>
        // add subtract  multiply  divide 用於計算的函式名
        function add(leftnum,rightnum){
            var res = leftnum+rightnum;
            document.getElementById('result').value = res;
        }
        function subtract(leftnum,rightnum){
            var res = leftnum-rightnum;
            document.getElementById('result').value = res;
        }
        function multiply(leftnum,rightnum){
        
            var res = leftnum*rightnum;
            document.getElementById('result').value = res;
        }
        function divide(leftnum,rightnum){
            if(rightnum == 0){
                alert("除數不能為0");
                return;
            }
            var res = leftnum/rightnum;
            
            document.getElementById('result').value = res;
        }
        function fn(){
            var str1=Number(document.getElementById('x').value);
            var str2=Number(document.getElementById('y').value);
            comp=document.getElementById('opt').value;
            var result;
            switch(comp) {
              case '0':
                add(str1,str2);
                break;
              case '1':
                subtract(str1,str2);
                break;
              case '2':
                multiply(str1,str2);
                break;
              case '3':
                divide(str1,str2);
                break;
            }
        }
      
    </script>
</body>

</html>

實現效果:

image-20210711131053815

缺點:

該程式碼的所有的方法以及變數都在全域性環境中,有汙染全域性環境的問題;

使用物件來封裝方法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>四則運算</title>
</head>
<body>
    <input type="text" id="x"/>
    <select name="" id="opt">
        <option value="0">+</option>
        <option value="1">-</option>
        <option value="2">*</option>
        <option value="3">/</option>
    </select>
    <input type="text" id="y"/>
    <button id="cal" onclick= "fn()">=</button>
    <input type="text" id="result"/>
    <script>
        // add subtract  multiply  divide 用於計算的函式名
        
        var calculator = {}; //放入其中
        calculator.add = function(leftnum,rightnum){
            var res = leftnum+rightnum;
            document.getElementById('result').value = res;
        }
        calculator.subtract = function (leftnum,rightnum){
            var res = leftnum-rightnum;
            document.getElementById('result').value = res;
        }
        
        calculator.multiply =  function (leftnum,rightnum){
            var res = leftnum*rightnum;
            document.getElementById('result').value = res;
        }
        calculator.divide =  function (leftnum,rightnum){
            if(rightnum == 0){
                alert("除數不能為0");
                return;
            }
            var res = leftnum/rightnum;
            
            document.getElementById('result').value = res;
        }
        function fn(){
            var str1=Number(document.getElementById('x').value);
            var str2=Number(document.getElementById('y').value);
            comp=document.getElementById('opt').value;
            switch(comp) {
              case '0':
                calculator.add(str1,str2);
                break;
              case '1':
                calculator.subtract(str1,str2);
                break;
              case '2':
                calculator.multiply(str1,str2);
                break;
              case '3':
                calculator.divide(str1,str2);
                break;
            }
        }
    </script>
</body>
    
</html>

實現效果:

缺點:

依舊存在屬性在全域性環境的問題;

使用閉包以及自執行函式實現計算器:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="x" />
    <select name="" id="opt">
        <option value="0">+</option>
        <option value="1">-</option>
        <option value="2">*</option>
        <option value="3">/</option>
    </select>
    <input type="text" id="y"/>
    <button id="cal">=</button>
    <input type="text" id="result" />
    <script>
        // 方法不會汙染全域性作用域
        var calculator = (function(){
            function add(x,y){
                return parseInt(x)+parseInt(y);
            }
            function subtract(x,y){
                return parseInt(x)-parseInt(y);
            }
            function multiply(x,y){
                return parseInt(x)*parseInt(y);
            }
            function divide(x,y){
                if(y == 0){
                    alert('除數不能為零');
                    return;
                }
                return parseInt(x)/parseInt(y);
            }
            return {
                add:add,
                subtract:subtract,
                multiply:multiply,
                divide:divide
            }
        })();
        var oX = document.getElementById('x');
        var oY = document.getElementById('y');
        var oOpt = document.getElementById('opt');
        var oCal = document.getElementById('cal');
        var oResult = document.getElementById('result');
        //事件監聽
        oCal.addEventListener('click',function(){
            var x = oX.value.trim();
            var y = oY.value.trim();
            var opt = oOpt.value;
            var result = 0;
            switch(opt){
                case '0':
                    result = calculator.add(x,y);
                    break;
                case '1':
                    result = calculator.subtract(x,y);
                    break;
                case '2':
                    result = calculator.multiply(x,y);
                    break;
                case '3':
                    result = calculator.divide(x,y);
            }
            oResult.value = result;
        })
        
   </script>
</body>
</html>

使用監聽器來實現click後的發生事件:

oCal.addEventListener('click',function(){
})

使用自執行函式與閉包縮小了方法的作用域,只在calculator物件呼叫方法後起作用。

var calculator = (function(){
    function add(x,y){
    }
    function subtract(x,y){
        
    }
    function multiply(x,y){
        
    }
    function divide(x,y){
   
    }
    //返回的是一個物件
    return {
        add:add,
        subtract:subtract,
        multiply:multiply,
        divide:divide
    }
})();

最終版:實現不改變原始碼的結構,增加功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="x" />
    <select name="" id="opt">
        <option value="0">+</option>
        <option value="1">-</option>
        <option value="2">*</option>
        <option value="3">/</option>
        <option value="4">%</option>
    </select>
    <input type="text" id="y"/>
    <button id="cal">=</button>
    <input type="text" id="result" />
    <script>
        // 方法不會汙染全域性作用域
        var calculator = (function(cal){
            function add(x,y){
                return parseInt(x)+parseInt(y);
            }
            function subtract(x,y){
                return parseInt(x)-parseInt(y);
            }
            function multiply(x,y){
                return parseInt(x)*parseInt(y);
            }
            function divide(x,y){
                if(y == 0){
                    alert('除數不能為零');
                    return;
                }
                return parseInt(x)/parseInt(y);
            }
            cal.add = add;
            cal.subtract = subtract;
            cal.multiply = multiply;
            cal.divide = divide;
            return cal;
            
        })(calculator || {});  // 採用自執行函式,如果沒有傳參的話則物件為空,有的話則正常傳參
        
        var calculator = (function(cal){
            cal.mod = function(x,y){
                return x%y;
            }
            return cal;
        })(calculator || {});  
        
        var oX = document.getElementById('x');
        var oY = document.getElementById('y');
        var oOpt = document.getElementById('opt');
        var oCal = document.getElementById('cal');
        var oResult = document.getElementById('result');
        //事件監聽
        oCal.addEventListener('click',function(){
            var x = oX.value.trim();
            var y = oY.value.trim();
            var opt = oOpt.value;
            var result = 0;
            switch(opt){
                case '0':
                    result = calculator.add(x,y);
                    break;
                case '1':
                    result = calculator.subtract(x,y);
                    break;
                case '2':
                    result = calculator.multiply(x,y);
                    break;
                case '3':
                    result = calculator.divide(x,y);
                case '4':
                    result = calculator.mod(x,y);
            }
            oResult.value = result;
        })
    </script>
</body>
</html>

執行效果:

image-20210711193903519

我們採用下面的這種格式實現所有方法以及屬性都不在全域性環境中:

var calculator = (function(cal){
    cal.mod = function(x,y){
        return x%y;
    }
    return cal;
})(calculator || {});

好處:可以靈活的增加功能並且增加功能與原來的功能的程式碼順序無所謂,

Node.js的前置知識:

全域性物件的使用:

// 全域性物件
global.foo = 'var';
console.log(global.foo);

簡單的http伺服器:

// 匯入http包
//require 是導包
var http = require('http');
// 建立伺服器
http.createServer(function(req,res)
{
    //有請求的話,響應返回:hello world
    res.end('hello world');
}).listen(3000,'127.0.0.1'); //監聽地址以及埠

使用方式:

image-20210711191051972

開啟瀏覽器:

輸入:http://127.0.0.1:3000或者localhost:3000

image-20210711191216882

結束方式:Ctrl-C

利用上述知識,實現模組之間的資料共享:

info.js

//node中一個js就是一個模組
//向外公開age變數
module.exports.age = '10';
// 公開一個函式
module.exports.sayHello = function(){
    console.log('hello');
}
var name = 'tom';

test.js

// 載入模組
var myModule = require('./info');
console.log(myModule);
myModule.sayHello();
console.log(myModule.name); //訪問不到

nodeJs實現計算器:

檔案目錄:

image-20210711191704219

add.js

module.exports = function add(x,y){
    return parseInt(x)+parseInt(y);
}

divide.js

module.exports = function divide(x,y){
    if(y == 0){
        alert('除數不能為零');
        return;
    }
    return parseInt(x)/parseInt(y);
}

multiply.js

module.exports = function multiply(x,y){
    return parseInt(x)*parseInt(y);
}

subtract.js

module.exports = function subtract(x,y){
    return parseInt(x)-parseInt(y);
}

index.js

module.exports = {
    add:require('./add'),
    subtract:require('./subtract'),
    multiply:require('./multiply'),
    divide:require('./divide')
};

我們訪問的就是index.js一個檔案即可

var cal = require('./index');
console.log(cal.add(1,2));
console.log(cal.subtract(1,2));
console.log(cal.multiply(1,2));
console.log(cal.divide(1,2));

實現效果:

image-20210711194312283

結束:

今天的知識點到這裡結束了,通過這些前置知識點,下一次將進行模組化的演變過程等;

如果你看到這裡或者正好對你有所幫助,希望能點個關注或者推薦,感謝;

有錯誤的地方,歡迎在評論指出,作者看到會進行修改。

相關文章