欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

JavaScript算术表达式计算器的代码实现

程序员文章站 2022-03-19 15:25:52
...
第一步,实现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算术表达式计算器的代码实现的详细内容,更多请关注其它相关文章!