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
?
2
Answers
If you use
func(...args)
, you won’t be setting thethis
value for this call offunc
and its value will depend on whether you’re in strict mode.In strict mode, it would be undefined but in sloppy mode, it’s the
window
object. See Default binding of the "this" keyword in strict modeYou don’t care about
this
if you use the spread syntax: