Home >Web Front-end >JS Tutorial >Detailed explanation of the sample code of JavaScript chain call calculator
A classic chain syntax calculator will look like this:
FluentCalculator.one.plus.two // 1 + 2 = 3 FluentCalculator.one.plus.two.plus.three.minus.one.minus.two.minus.four // -1 FluentCalculator.one.plus.ten - 10 // 1 + 10 - 10 = 1
If called abnormally, undefined will be returned:
FluentCalculator.one.one // undefined,因为值不能调用值 FluentCalculator.one.plus.plus // undefined,操作不能连续调用
For this problem, we have to determine an idea : There are states passed between each call, and there are two states.
When the value (num) call ends, the operation status object (OprStatus) is returned.
When the operation (opr) call ends, the value status object (NumStatus) is returned.
In other words, these two states are alternating. If there is no alternation, it is an abnormal call and undefined will be returned.
"use strict"; var num = ["zero","one","two","three","four","five","six","seven","eight","nine","ten"]; var oprs = {plus : "+",minus : "-",times : "*",pidedBy : "/"}; var Magic = {}; //状态对象,父对象 function Status(value,opr){ //当前运算结果 this.value = value; //当前操作符 this.opr = opr; } //值状态对象,继承状态对象 function NumStatus(value,opr){ Status.call(this,value,opr); } //操作状态对象,继承状态对象 function OprStatus(value,opr){ Status.call(this,value,opr); } //给值状态对象原型上绑定方法 for(let i=0;i<num.length;i++){ Object.defineProperty(Magic,num[i],{ get : function(){ var val; if(!this.opr){ val = i; } else{ switch(this.opr){ case "+":val = this.value + i;break; case "-":val = this.value - i;break; case "*":val = this.value * i;break; case "/":val = this.value / i;break; } } //返回操作状态对象 return new OprStatus(val,null); } }); } //给操作状态对象原型上绑定方法 for(let i in oprs){ if(oprs.hasOwnProperty(i)){ Object.defineProperty(OprStatus.prototype,i,{ get : function(){ //返回值状态对象 return new NumStatus(this.value,oprs[i]); } }); } } var FluentCalculator = Magic; NumStatus.prototype = Magic; //所有调用结束时,就会调valueOf打印,直接返回最终运算结果 OprStatus.prototype.valueOf = function(){ return this.value; };
The above is the detailed content of Detailed explanation of the sample code of JavaScript chain call calculator. For more information, please follow other related articles on the PHP Chinese website!