Your function memoize
returns a new function which caches the results, if a function call with the same first parameter (e.g. 1
) has been made.
function#apply
takes two arguments:
- The current context (a.k.a.
this
in your function)
- The array(-like) of arguments you would like to pass in.
this
simply refers to the context that your function is called in. Passing it into apply
simply ensures that your memoized function continues to work as one would expect from a regular JS function.
A few examples:
var a = function(number) {
console.log(this);
}
var b = _.memoize(a);
a(1); // this refers to window
b(1); // this refers to window as well
a.call({ test: true }); // this refers to { test: true }
b.call({ test: true }); // this refers to { test: true } as well
If you were to pass null
for example instead of this
as the first argument of func.apply
…
cache[n] = func.apply(null, arguments);
…it would not work anymore:
a(1); // this refers to window
b(1); // this refers to window as well
a.call({ test: true }); // this refers to { test: true }
b.call({ test: true }); // this refers to window
and in strict mode, this
would always be null
for b
.