第一步,實作createOperator函數,傳回閉包函數:
var Add = createOperator("+" , function(a,b){return a + b;}); var Minus = createOperator("-" , function(a,b){return a - b;}); var Mul = createOperator("*" , function(a,b){return a * b;}); var pide = createOperator("/" , function(a,b){return a / b;});
1.閉包函數的實例,擁有eval和toString兩個方法
2.eval方法負責計算算術表達式的值
3.toString方法將表達式的計算過程以字串形式展示
4.適用範圍僅限於二目運算子
var a = new Add(new Value(3), new Value(5)); //8 console.log(a.eval()); //"3 + 5" console.log(a.toString()); var b = new Mul(new Value(6), new Value(2)); //12 console.log(b.eval()); //"6 * 2" console.log(b.toString()); var c = new Add(a,b); //20 console.log(c.eval()); //"3 + 5 + 6 * 2" console.log(c.toString());
運算過程中的值都會用Value的形式儲存
function Value(value){ this.value = value || 0; } Value.prototype.toString = function(){ return this.value.toString(); };
createOperator函數的程式碼實作:
//IIFE var createOperator = (function() { //name:"+","-","*","/" //oper:对应的加减乘除函数 return function(name, oper){ //闭包函数 var Foo = function(){ //获取2个操作数 var args = arguments; var nums = [].slice.call(arguments); nums = nums.map(function(e){return e.value;}); var val = new Value(oper.apply(null,nums)); //给实例绑定toString和eval方法 val.toString = function(){ return args[0].toString() + " " + name + " " + args[1].toString(); }; val.eval = function(){ return this.value; }; return val; }; return Foo; }; })();
以上是JavaScript算術表達式計算器的程式碼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!