14

私のコードベースには次の行があります。

var uncurryThis = Function.bind.bind(Function.call);

私が取り組もうとしていること。おそらく、それはアンカレーです。どうすればこれを解決できますか?

にバインドされてFunction.bindいるのバージョンだと思います。役に立ちません。そして、私は使用法を見つけていないので、それをスタンドアロンと呼ぶのか、それとも「メソッドとして」呼び出す必要があるのか​​さえわかりません。最初にバインドするだけです。thisFunction.call

4

4 に答える 4

6

わかった。あなたは何を知ってbindいますか?関数の引数を固定しthis、新しい関数を返すメソッドです。次のように簡略化できます。

function bind(context) {
    var fn = this;
    return function() {
        return fn.apply(context, arguments);
    };
}

多くの部分的なアプリケーションを使用して、より機能的なスタイルでコンテキストを使用して関数呼び出しを省略します: bind fn (context) -> fn context。引数付き: (bind fn (context))(…) は fn context (… ) と同じです。

同様に、calldo は値を取りthisますが、関数を返す代わりに、今すぐ適用します: call fn (context, …) -> fn context (…)。

それでは、コードを見てみましょう: bind.call(bind, call). ここでは、この値として適用bindbindています: bind bind (call)。これを (上記のルールで) bind callに拡張しましょう。これにいくつかの引数を指定するとどうなるでしょうか?call

bind bind (call) (fn)(context, …)

bind call (fn)(context, …)

fnを呼び出す(コンテキスト、…)

fnコンテキスト(…)

一歩一歩、私たちはできる

uncurryThis = bind bind (call) //bind call

func = uncurryThis(メソッド)メソッド//の呼び出し

結果 = func(context, …)//メソッドのコンテキスト(…)

これの実用的な使用例は、最初の引数としてオブジェクト (メソッドが呼び出される) を取る、静的関数に変換されることになっている「クラス」メソッドです。

var uncurryThis = Function.bind.bind(Function.call);
var uc = uncurryThis(String.prototype.toUpperCase);
uc("hello") // in contrast to "hello".toUpperCase()

これは、メソッド呼び出しを配置できないが、静的関数が必要な場合に役立ちます。例えばのように

["hello", "world"].map(uc) // imagine the necessary function expression

また、呼び出したいメソッドは、次のようにオブジェクト自体のメソッドではない場合があります。

var slice = uncurryThis(Array.prototype.slice);
slice(arguments) // instead of `Array.prototype.slice.call(arguments)` everywhere

それが役立つ場合は、バインドなしの明示的な実装もここにあります。

function uncurryThis(method) {
    return function(context/*, ...*/)
        return method.apply(context, Array.prototype.slice.call(arguments, 1));
    };
}
于 2014-05-06T00:33:30.940 に答える
0

関数で bind を呼び出すと、コンテキストに置き換えられた新しい関数が返されます。

function random() {
  alert(this.foo);
}
var newRandom = random.bind({foo:"hello world"}) //return new function same as //`random` with `this` is replaced by object {foo:"hello world"}

私たちが持っているのと同じです:

Function.bind.bind(Function.call)
// return new Function.bind with its `this` is replaced by `Function.call`

bind次のソースがあります( @Bergiによって提供された関数の簡略化されたバージョンを使用):

var bb = function bind(context){
  var fn = Function.call;
  return function() {
        return Function.call.apply(context, arguments); //also replace fn here for easier reading
    };
}

ここでのコンテキストは関数になることに注意してください。たとえばrandom、 bb(random) を呼び出すと、関数は次のようになりますnewRandom

newRandom = function(){
   return Function.call.apply(random, arguments); //also replace 
}
//`apply` function replace `this` of Function.call to `random`, and apply Function(now become `random`) with arguments in `arguments` array.
于 2015-06-01T02:01:00.567 に答える