The function memoize
creates a new function that stores the results in a cache, if the same function call with the same first parameter (e.g. `1`) has been previously made.
The function#apply
method requires two arguments:
- The current context (referred to as `this` within your function)
- An array or array-like object containing the arguments you want to pass in.
In JavaScript, `this` represents the execution context of a function. Using it with `apply` ensures that the memoized function retains its functionality similar to a regular JS function.
Here are a few examples:
var a = function(number) {
console.log(this);
}
var b = _.memoize(a);
a(1); // `this` refers to window
b(1); // `this` also refers to window
a.call({ test: true }); // `this` refers to { test: true }
b.call({ test: true }); // `this` still refers to { test: true }
If you were to pass `null` instead of `this` as the first argument for `func.apply`...
cache[n] = func.apply(null, arguments);
...the function would not work correctly anymore:
a(1); // `this` refers to window
b(1); // `this` still refers to window
a.call({ test: true }); // `this` refers to { test: true }
b.call({ test: true }); // `this` now refers back to window
In strict mode, `this` would always be `null` for function `b`.