第一步,实现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中文网其他相关文章!