0

これら2つの機能の違いは何ですか?

function bind_1(f, o) {
    if (f.bind)
        return f.bind(o);
    else
        return function() { return f.apply(o. arguments); };
}

function bind_2(f, o) {
    if (f.bind)
        return f.bind(o);
    else
        return f.apply(o. arguments);
}
4

3 に答える 3

3

VadimとCorbinはどちらもほぼ正しいですが、少し具体性と冗長性を追加するために(私は大きな言葉を話します)、bind_1は、指定された引数(o)をコンテキストとして設定して指定された関数(f)を常に呼び出す関数を返します-設定コンテキストとは、関数内でthisキーワードが割り当てられたコンテキストオブジェクトを参照することを意味します。一方、 bind_2は、コンテキスト(o)を使用して関数(f)を返す、コンテキスト(o)を使用して関数(f)を呼び出した結果を返します。

Function.prototype.bindは、部分機能の適用にも使用できます。たとえば、関数内でコンテキストを使用する必要がない場合は、引数がすでに適用されている関数を提供できるため、後続の呼び出しが簡略化されます。

// define a function which expects three arguments
function doSomething (person, action, message) {
    return person + " " + action + " " + message + ".";
}

var shortcut = doSomething.bind(null, "Joshua", "says");
// the call to bind here returns a function based on doSomething with some changes:
// 1. the context (_this_) is set to null
// 2. the arguments (person and action) are defined ("Joshua" and "says") and not changeable

// now we can use shortcut("Hello")
// instead of doSomething("Joshua", "says", "Hello")
shortcut("Hello"); // returns "Joshua says Hello."

The first argument passed to .apply(), .call(), or .bind() is changing the context of the function/method. The context is the value of the this keyword; thus, inside of the function the this value will be whatever is passed as the first argument. Here I was using null because in this case the function doesn't need a specific value for the context; and null is fewer characters than undefined, and feels better than some garbage value ("" - empty string, {} - empty object, etc.). So the remaining two variables are assigned as the first set of arguments to the function.

function exampleContext () {
    return this; // context of function execution
}

exampleContext(); // returns the global scope "window" (in the browser)

var exampleBind = exampleContext.bind(null);
exampleBind(); // returns "null"

var exampleBind = exampleContext.bind("Joshua");
exampleBind(); // returns "Joshua"

var exampleBind = exampleContext.bind({});
exampleBind(); // returns "Object {}""
于 2012-05-12T10:07:35.217 に答える
1

bind_1は、呼び出されたときに。で実行fされる関数を返しますo.arguments

bind_2はすぐに。で実行fされo.argumentsます。

この「必要性」については、すぐにわかるものはありません。ある人のコードのある文脈では、それは明らかに目的を持っています。

于 2012-05-12T08:54:01.410 に答える
0

ほとんどの場合this、関数に異なるコンテキスト(値)を「アタッチ」するために行われます。

于 2012-05-12T09:20:30.147 に答える