4

Function.prototype.bind の最初の引数を「定義」できず、呼び出されたコンテキストを保持できない理由はありますか?

これを行うと非常に便利なユースケースがありますが、最初の引数が出力関数をウィンドウにバインドするため、null または未定義を渡すように見えます。

別の言い方をすれば、現在のネイティブ バインドの実装では、関数のコンテキストをバインドせず、バインドされた関数に引数プレフィックスのみをバインドすることはできないようです。

元:

var a = function() { 
    this.foo = function() { console.log(this) }; 
    this.foo = this.foo.bind(undefined,1); 
};
var b = new a();
b.foo(); // Logs Window instead of the instance b;

これは、Google Chrome バージョン 27.0.1453.116 m でテストされました。

4

1 に答える 1

2

これを行うには、独自のバインダー関数を作成する必要があります。持つ主な理由は.bind()、字句的に定義されていない を処理することでしたthis。そのため、設定せずに使用する方法は提供されていませんthis

使用できる簡単な例を次に示します。

Function.prototype.argBind = function() {
    var fn = this;
    var args = Array.prototype.slice.call(arguments);

    return function() {
        return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
    };
};

これは非常に必要最低限​​の機能であり、コンストラクターとして呼び出される関数を処理しませんが、必要に応じてそのサポートを追加できます。


orが最初の引数として渡され.bind()ない限り、ネイティブのように動作するように拡張することもできます。nullundefined

Function.prototype.argBind = function(thisArg) {
    // If `null` or `undefined` are passed as the first argument, use `.bind()`
    if (thisArg != null) {
        return this.bind.apply(this, arguments);
    }

    var fn = this;
    var args = Array.prototype.slice.call(arguments);

    return function() {
        return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
    };
};
于 2013-06-27T23:20:19.217 に答える