JavaScript Function bind()
- 前のページ JS ファンクション Apply
- 次のページ JS 闭包
関数の借用(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
参照グローバルオブジェクト。 - 関数内で、厳格モードでは、
this
はundefined
。 - イベント内で、
this
イベントを受け取る要素。 - call()、apply()、bind()などのメソッドを使用して、
this
参照到どんなオブジェクトも。
注意:this
は変数ではありません。それはキーワードです。変更することはできません this
の値。
も参照してください:
チュートリアル:JavaScript this
- 前のページ JS ファンクション Apply
- 次のページ JS 闭包