skip to Main Content

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


  1. If you use func(...args), you won’t be setting the this value for this call of func 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 mode

    Login or Signup to reply.
  2. You don’t care about this if you use the spread syntax:

    function memoize(func) {
      const cache = {}
      return function(...args) {
        return cache[JSON.stringify(args)] ??= func(...args);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search