前回 JavaScript での引数束縛を扱った際には引数リストの先頭からの束縛だったが、ななしさんによる Array#splice
を使った方法を応用すれば任意の引数の束縛も比較的簡単な形で書ける。C++ には bind1st
、bind2nd
というのがあるそうだが、それと同じようなことができるわけだ。
Function.prototype.bindNth = function (/* n, arg, ... */) {
var self = this;
var args = arguments;
args[0]--;
Array.prototype.splice.call(args, 1, 0, 0);
return function () {
Array.prototype.splice.apply(arguments, args);
return self.apply(this, arguments);
};
};
function concat(a, b) {
return "" + a + b;
}
alert( concat.bindNth(1, "a")("b") ); // "ab"
alert( concat.bindNth(2, "a")("b") ); // "ba"
セコメントをする