I came across the following thing while trying to understand some concepts of working with closures.
When I was reading about memoization/throttling, people were using func.apply(this, args)
in closures.
Here are some examples from 2 different sources:
function memoize(func) {
const cache = {}
return function(...args) {
const key = JSON.stringify(args)
if (cache[key]) {
return cache[key]
} else {
const result = func.apply(this, args) // (*)
cache[key] = result
return result
}
}
}
and
function throttle(func, interval) {
let isRunning = false;
return function (...args) {
if (!isRunning) {
isRunning = true;
func.apply(this, args); // (*)
setTimeout(() => {
isRunning = false;
}, interval);
}
};
}
So my question is: can we use func(...args)
instead? And what is the actual difference if we would call func
with spread-operator instead of apply
?