名著JavaScript:the good parts 「良いパーツ」によるベストプラクティス [ ダグラス・クロフォード ]覚書
私が買ったのは,2010年10月13日 初版第6刷発行
P96にbindメソッドの定義が載っている。その説明が,
「関数を渡したオブジェクトのメソッドであるかのように呼び出す関数を返す。」
これ,何言ってるのかが分からなかった。英語での説明は
「Return a function that will call this function as
though it is a method of that object.」
読点を入れる。
「関数を,渡したオブジェクトのメソッドで
あるかのようにして呼ぶことのできる関数を返す。」
つまり,「(関数)=(渡したオブジェクトのメソッド)であるかのように呼び出すことができる関数を返す」のがbindメソッドである。
と解釈した。
2018年の時点でFunction.prototype.bindはもう,ほとんどのブラウザで定義されているので,自分で定義する必要がない。
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Function.method('bind', function (that) {
// Return a function that will call this function as
// though it is a method of that object.
var method = this,
slice = Array.prototype.slice,
args = slice.apply(arguments, [1]);
return function () {
return method.apply(that,args.concat(slice.apply(arguments, [0])));
};
});