# 创建计算器 (JS)

[英]Create calculator (JS)

class Calc{ constructor(num){ this.num = num } add(a){ this.num += a; return this; } res() { return this.num; } } let calc = new Calc(2) console.log(calc.add(3).add(5).res())

but in my case I pass 2 in new Calc(2) , not in calc(2) .但在我的情况下，我在new Calc(2)传递2 ，而不是在calc(2) How can I change it?我怎样才能改变它？

Will be really grateful for any help!将不胜感激任何帮助！

If I understood correctly, this would be a way to do it:如果我理解正确，这将是一种方法：

class Calc{ constructor(num){ this.num = num } add(a){ this.num += a; return this; } res() { return this.num; } } let calc = function(num){ return new Calc(num) } console.log(calc(2).add(3).add(5).res())

You can have an elegant solution leveraging the power of closures:你可以有一个优雅的解决方案，利用闭包的力量：

function calc(x) { return { res: function() { return x; }, add: function(y) { return calc(x + y) } } } test( 10, calc(10).res() ); test( 10, calc(3).add(7).res() ); test( 10, calc(8).add(2).res() ); test( 10, calc(2).add(3).add(5).res() ); function test(expected, actual) { console.log( `result is: \${actual} correct: \${actual === expected} `) }

The calc function takes the initial number called x and returns an object with two methods: calc函数采用名为x的初始数字并返回一个具有两种方法的对象：

• res() just returns the number res()只返回数字
• add() will take a parameter y , sums it with x and calls calc again with the result. add()将接受一个参数y ，将它与x相加并再次使用结果调用calc

The code can be shortened a lot using arrow functions:使用箭头函数可以大大缩短代码：

const calc = x => ({ res: () => x, add: y => calc(x + y) }); test( 10, calc(10).res() ); test( 10, calc(3).add(7).res() ); test( 10, calc(8).add(2).res() ); test( 10, calc(2).add(3).add(5).res() ); function test(expected, actual) { console.log( `result is: \${actual} correct: \${actual === expected} `) }

Other operations can also easily be added using the same pattern:使用相同的模式也可以轻松添加其他操作：

const calc = x => ({ res: () => x, add: y => calc(x + y), sub: y => calc(x - y), mul: y => calc(x * y), div: y => calc(x / y) }); test( 2, calc(5).add(5).mul(2).sub(4).div(8).res() // (((5 + 5) * 2) - 4) / 8 = // ((10 * 2) - 4) / 8 = // (20 - 4) / 8 = // 16 / 8 = 2 ); function test(expected, actual) { console.log( `result is: \${actual} correct: \${actual === expected} `) }

Note that since each operation is executed immediately, so the only precedence you currently have is what comes first.请注意，由于每个操作都是立即执行的，因此您当前拥有的唯一优先级是最先出现的。

You can define calc as function that returns Calc object.您可以将calc定义为返回 Calc 对象的函数。

class Calc{ constructor(num){ this.num = num } add(a){ this.num += a; return this; } res() { return this.num; } } const calc = (input) => new Calc(input); console.log(calc(2).add(3).add(5).res())