【发布时间】:2019-07-17 12:27:32
【问题描述】:
我需要创建一个包装函数来调用具有给定次数num 的函数multiply 以允许执行multiply。 nTimes(num,2) 然后分配给runTwice -- runTwice 可以是调用nTimes 函数的任何函数,该函数给出不同的num 输入--
就我而言,为简单起见,我只允许它运行 2 次 num=2
如果我们第一次和第二次运行runTwice 函数,它将返回multiply 函数使用multiply 的输入计算的结果。第二次之后的任何调用都不会运行multiply 函数,但会返回multiply 函数的最新结果。
这是我的实现,它使用一个对象来跟踪我们执行函数的次数、允许执行的最大次数以及 multiply 的最新结果
'use strict'
//use a counter object to keep track of counts, max number allowed to run and latest result rendered
let counter = {
count:0,
max: 0,
lastResult: 0
};
let multiply = function(a,b){
if(this.count<this.max){
this.count++;
this.lastResult = a*b;
return a*b;
}else{
return this.lastResult;
}
}
// bind the multiply function to the counter object
multiply = multiply.bind(counter);
let nTimes=function(num,fn){
this.max = num;
return fn;
};
// here the nTimes is only executed ONE time, we will also bind it with the counter object
let runTwice = nTimes.call(counter,3,multiply);
console.log(runTwice(1,3)); // 3
console.log(runTwice(2,3)); // 6
console.log(runTwice(3,3)); // 6
console.log(runTwice(4,3)); // 6
请注意,我对简单的multiply 进行了相当多的更改,并将其绑定到counterobject 以使其工作。还使用调用nTimes 绑定counter 对象。
如何使用包装函数实现相同的结果,但对简单的multiply 函数的更改较少?
假设multiply函数很简单:
let multiply = function(a,b){ return a*b };
【问题讨论】:
标签: javascript wrapper execute