LoginSignup
13
13

More than 5 years have passed since last update.

javascript - bind関数について

Posted at
  • ある関数が呼ばれた時の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

参考

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13