Home > Web Front-end > JS Tutorial > Code implementation of JavaScript arithmetic expression calculator

Code implementation of JavaScript arithmetic expression calculator

黄舟
Release: 2017-03-18 14:53:51
Original
1555 people have browsed it

The first step is to implement the createOperator function and return the closure function:

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;});
Copy after login

1. An instance of the closure function has two eval and toString Method

2. The eval method is responsible for calculating the value of the arithmetic expression

3. The toString method uses the string form to calculate the expression Display

4. The scope of application is limited to binary Operator

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());
Copy after login

The values ​​during the operation are stored in the form of Value

function Value(value){
    this.value = value || 0;
}

Value.prototype.toString = function(){ 
	return this.value.toString(); 
};
Copy after login

createOperator function Code implementation:

//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;
    }; 
})();
Copy after login

The above is the detailed content of Code implementation of JavaScript arithmetic expression calculator. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template