- ある関数が呼ばれた時のthisの値を固定する
- 返り値は(thisが固定された)
元の関数
と同じ新しい関数 - 引数の固定とかもできる
実行環境
- node.js v0.11.13
thisの値を固定
bind.js
function hoge() {
console.log(this);
};
var bindAri = hoge.bind('ringo');
var bindNasi = hoge;
console.log(bindAri);
console.log(bindNasi);
bindAri();
console.log('\n===========\n');
bindNasi();
実行結果
$ node bind.js
[Function]
[Function: hoge]
[String: 'ringo']
===========
{ DTRACE_NET_SERVER_CONNECTION: [Function],
DTRACE_NET_STREAM_END: [Function],
…(以下略
引数を固定
bind2.js
function sum(a,b,c) {
console.log(this);
console.log(arguments);
return a+b+c;
};
var hoge = sum.bind(20, 100, 2);
console.log('a+b+c = ' + hoge(5,11));
実行結果
$ node bind2.js
[Number: 20]
{ '0': 100, '1': 2, '2': 5, '3': 11 }
a+b+c = 107