関数memoize
は、同じ第1パラメータ(たとえば1
)を持つ関数呼び出しが行われた場合に、結果をキャッシュする新しい関数を返します。
function#apply
は2つの引数を取ります。
- あなたが渡したい引数の現在のコンテキスト(別名
this
あなたの関数内)
- 配列(様)
this
apply
に渡すだけで、通常のJS関数から期待されるように、memoized関数が機能し続けることが保証されます。
いくつかの例:
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
あなたが例えばnull
代わりのfunc.apply
の最初の引数としてthis
を渡すとしたら...
cache[n] = func.apply(null, arguments);
...それはもう機能しません。
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
およびstrict mode、this
は、b
の場合、常にnull
になります。
「このキーワードはどのように機能しますか?」(http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – 4castle
これは素晴らしい説明だと思います「これ」がどのように縛られているのか。 https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/ch2.md – BrianDiesel