How to use JavaScript to implement a simple encapsulation function for arithmetic expression computation can help us record the computation process. Step 1: 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;});
1. The closure function instance has two methods: eval and toString.
2. the eval method is used to calculate the value of an arithmetic expression.
3. The toString method displays the expression calculation process in string format.
4. The applicability is limited to binary operators.
var a = new Add(new Value(3), new Value(5));//8console.log(a.eval());//"3 + 5"console.log(a.toString());var b = new Mul(new Value(6), new Value(2));//12console.log(b.eval());//"6 * 2"console.log(b.toString());var c = new Add(a,b);//20console.log(c.eval());//"3 + 5 + 6 * 2"console.log(c.toString());
Values are stored in the form of values during calculation.
function Value(value){ this.value = value || 0;}Value.prototype.toString = function(){ return this.value.toString(); };
Code Implementation of the createOperator function:
// IIFEvar createOperator = (function () {// name: "+", "-", "*", "/" // OPERATOR: return function (name, struct) {// closure function var Foo = function () {// obtain two operands var args = arguments; var nums = []. slice. call (arguments); nums = nums. map (function (e) {return e. value ;}); var val = new Value (values. apply (null, nums); // bind toString and eval methods to the instance val. toString = function () {return args [0]. toString () + "" + name + "" + args [1]. toString () ;}; val. eval = function () {return this. value ;}; return val ;}; return Foo ;};})();
The above is the code implementation of the JavaScript arithmetic expression calculator. For more information, see other related articles in the first PHP community!