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

なぜthisがfunc.applyで使用されているのか理解しようとしています...それは何を参照していますか?memoizeのこのjs実装内でこの適用を使用する際に「これ」とは何ですか?

+0

「このキーワードはどのように機能しますか?」(http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – 4castle

+0

これは素晴らしい説明だと思います「これ」がどのように縛られているのか。 https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/ch2.md – BrianDiesel

答えて

1

関数memoizeは、同じ第1パラメータ(たとえば1)を持つ関数呼び出しが行われた場合に、結果をキャッシュする新しい関数を返します。

function#applyは2つの引数を取ります。

  1. あなたが渡したい引数の現在のコンテキスト(別名thisあなたの関数内)
  2. 配列(様)

thisapplyに渡すだけで、通常の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 modethisは、bの場合、常にnullになります。

関連する問題