JavaScript Function bind()

関数の借用(Function Borrowing)

bind() メソッドを使用することで、1つのオブジェクトが別のオブジェクトのメソッドを借用できます。

以下の例では、2つのオブジェクト(person と member)が作成されています。

member オブジェクトは person オブジェクトの fullname メソッドを借用しています:

const person = {
  firstName: "Bill",
  lastName: "Gates",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}
const member = {
  firstName: "Hege",
  lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);

自分で試してみてください

this を保持

時には bind() メソッドを使用して this を失われないようにする必要があります。 this

以下の例では、person オブジェクトに display メソッドがあります。display メソッドでは、this は person オブジェクトを指します:

const person = {
  firstName: "Bill",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
person.display();

自分で試してみてください

関数がコールバックとして使用される場合、this 失われます。

この例では、3秒後に名前を表示しようとしますが、表示されるのは undefined

const person = {
  firstName: "Bill",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
setTimeout(person.display, 3000);

自分で試してみてください

bind() メソッドがこの問題を解決します。

以下の例では、bind() メソッドを使用して person.display を person にバインドしています。

この例では、3秒後に名前を表示します:

const person = {
  firstName: "Bill",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
let display = person.display.bind(person);
setTimeout(display, 3000);

自分で試してみてください

this とは何ですか?

JavaScriptでは、this キーワードが参照オブジェクト

参照どのオブジェクトは呼び出し(使用または呼び出し)の方法に依存します。

使用方法によって、キーワード this 異なるオブジェクトを参照します:

  • オブジェクトメソッド内で、this このオブジェクト
  • 単独で使用するとき、this 参照グローバルオブジェクト
  • 関数内で、this 参照グローバルオブジェクト
  • 関数内で、厳格モードでは、thisundefined
  • イベント内で、this イベントを受け取る要素
  • call()、apply()、bind()などのメソッドを使用して、 this 参照到どんなオブジェクトも

注意:this は変数ではありません。それはキーワードです。変更することはできません this の値。

も参照してください:

チュートリアル:JavaScript this