LoginSignup
1
2

More than 3 years have passed since last update.

誰でもわかるJavascript - bind編

Last updated at Posted at 2020-05-15

Javascriptのbindの記事を読んでも、さっぱりわからないという人(自分)のために解説してみる。

bindの基本

以下のオブジェクトが定義されているとする。

const person = {
  age: 20,
  displayAge: function() { console.log(this.age); }
};

personオブジェクトを通してdisplayAge関数を実行すると「20」が表示される。

person.displayAge(); // 20

displayAge関数を変数に代入して、実行すると何故か「undefined」が表示されてしまう。

const newDisplayAge = person.displayAge;
newDisplayAge(); // undefined

newDisplayAgeの中身を見てみると当然displayAge関数が代入されている。
しかし、thisが何であるかわからない状態になっている。1

this?
console.log(newDisplayAge); // function() { console.log(this.age); } 

そこでbind関数を使うとthisが何であるかを教えてあげることで正常に動作する。

const bindDisplayAge = person.displayAge.bind(person);
bindDisplayAge(); // 20

bindの応用

bindの第1引数にはthis、それ以降の引数には関数に渡す引数が定義できる。
以下のコードではgreet関数にthisが使用されていない。
そのため、第1引数にはnull渡し、第2引数でgreet関数のname引数に'taro'を渡している。2

const person = {
  greet: function(name) { console.log('hello ' + name); }
};

const greetPerson = person.greet.bind(null, 'taro');
greetPerson(); // hello taro

どういう時に使うのか

関数を実行したくないが、呼び出すだけで実行できる状態にしておきたいときに使う。
具体的な例としてボタンが押された時のイベントハンドラーにthisや引数が使用されている場合、bindが必要になる。

const person = {
  age: 20,
  displayAge: function() { console.log(this.age); }
};
const button = document.querySelector('button');

// 以下は想定の動作とは異なる。
button.addEventListener('click', person.displayAge()); // ページ読み込み後に'20'が表示
button.addEventListener('click', person.displayAge);   // ボタンクリック時に'undefined'が表示

// 正常に動作する。
button.addEventListener('click', person.displayAge.bind(person)); // ボタンクリック時に'20'が表示

  1. 正確に書くとブラウザで実行した場合、thisはWindowオブジェクト 

  2. 第1引数にpersonを渡してもエラーにはならない 

1
2
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
1
2