Skip to content

Instantly share code, notes, and snippets.

@think49
Last active April 22, 2018 14:54
Show Gist options
  • Save think49/59c9b5b7ca5b0b15cea5192046549fdf to your computer and use it in GitHub Desktop.
Save think49/59c9b5b7ca5b0b15cea5192046549fdf to your computer and use it in GitHub Desktop.
bind-from-function.js: 任意のインデックスの引数束縛した関数を生成

bind-from-function.js

概要

Function.prototype.bind は引数束縛、またはthis 値を束縛した関数を生成しますが、次の制限があります。

  • this 値を束縛しなければ、引数束縛できない
  • 引数束縛はインデックスの若い番号から順番に束縛する事しか出来ない (例: arguments[1] を束縛するには、arguments[0] も束縛しなければならない)

bind-from-function.js はこれらの欠点を克服します。

  • this 値を束縛せず、引数束縛のみ実施した関数を生成できる
  • 任意のインデックスの引数のみを束縛できる (例: arguments[0] は束縛せず、arguments[1] のみ束縛できる)

制約

  • 現行版では、第二引数で iterator を指定できません (ToDo: Array.from)

使い方

bindFromFunction (fn, args [, thisArg])

第一引数に指定した関数を、第二引数で指定した引数(配列)に束縛し、束縛した関数を返します。

const args = [,10]; // 第二引数に 10 を指定する (第一引数は束縛しない)

console.log(parseInt('0xFF'));      // 255
console.log(parseInt('0xFF', 10));  // 0
console.log(bindFromFunction(parseInt, args)('0xFF')); // 0

第三引数で this 値を指定できます(オプション)。

console.log(Array.prototype.slice.bind([1,2,3])(1));  // [2, 3]
console.log(bindFromFunction(Array.prototype.slice, [], [1,2,3])(1)); // [2, 3]

(※比較のために併記しましたが、Function.prototype.bind で実装可能な場合は、あえて bindFromFunction()` を使用する必要はありません。)

リンク

/**
* bind-from-function.js
* Create a function with arguments and this bound.
*
* @version 1.0.0
* @author think49
* @url https://gist.github.com/think49/59c9b5b7ca5b0b15cea5192046549fdf
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
'use strict';
function bindFromFunction (fn, bindArgs, ...bindThisArg) {
return function (...args) {
let i = bindArgs.length;
while (i--) {
if (bindArgs.hasOwnProperty(i)) {
args[i] = bindArgs[i];
}
}
return !bindThisArg.length ? fn.apply(this, args) : fn.apply(bindThisArg[0], args);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment