1
_.memoize = function(func) {
  var cache = []; 
  return function(n){
    if(cache[n]){
        return cache[n];
    }
    cache[n] = func.apply(this,arguments);
    return cache[n];
  }
};

I'm just trying to understand why 'this' is used in func.apply here...What does it refer to?

Jon
  • 61
  • 3
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – 4castle Jun 29 '16 at 16:35
  • I think this is a great explanation of how "this" is bound. https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/ch2.md – BrianDiesel Jun 29 '16 at 16:56

1 Answers1

1

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:

  1. The current context (a.k.a. this in your function)
  2. 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.

nils
  • 20,884
  • 5
  • 60
  • 75