如何将函数与javascript闭包和对象连接起来



我正试图找到这个练习的解决方案:

实现添加一个对象的计算函数,该对象能够执行以下四项操作对同一个数字进行数学运算(加法、减法、乘法和除法(,最后打印出结果。

function calculate() {
}
const calculator = calculate();
calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(calculator)

那么,解决这个问题的正确方法是什么(如果你能添加评论,将不胜感激

不需要放那么多thisfunction。。。

这样就有了闭包值
=>calc_00.val = 20;
不会更改结果(如果jso未冻结,它只添加一个新属性(或者在严格模式中抛出错误

"use strict";
function calculate( initVal = 0 )  // default value is zero
{
let
val = initVal    // closure value
, jso =
{ add(v)         { val += v; return this }
, sub(v)         { val -= v; return this }
, multiply(v)    { val *= v; return this }
, divide(v)      { val /= v; return this }
, printResult()  { return val }
}
Object.freeze(jso)

return jso
}
const
calc_00 = calculate()
, calc_10 = calculate(10)
;
// calc_00.yop = ()=>null; // Uncaught TypeError: can't define property "yop": Object is not extensible
// calc_00.sub = ()=>null; // Uncaught TypeError: "sub" is read-only
// calc_00.val = 20;       // Uncaught TypeError: can't define property "val": Object is not extensible
calc_00.add(2).add(4).multiply(3).sub(1).sub(3).divide(2);
calc_10.add(10).multiply(3);
console.log( calc_00.printResult(), calc_10.printResult() ) // 7 , 60

您可以返回对象本身。

function calculate() {
return {
result: 0,
add: function(num) {
this.result += num;
return this;
},
sub: function(num) {
this.result -= num;
return this;
},
multiply: function (num) {
this.result *= num;
return this;
},
divide: function (num) {
this.result /= num;
return this;
},
printResult: function () {
return this.result;
}
}
};
const calculator = calculate();
const result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(result);

确保了解this在JavaScript中的工作原理。例如,使用函数与使用箭头函数不同。

参考:JavaScript这个

使用闭包的替代解决方案

function calculate() {
let result = 0;
return {
add: function(num) {
result += num;
return this;
},
sub: function(num) {
result -= num;
return this;
},
multiply: function (num) {
result *= num;
return this;
},
divide: function (num) {
result /= num;
return this;
},
printResult: function () {
return result;
}
}
};
const calculator = calculate();
const result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(result);

最新更新