bind()
JavaScript でのの使用法は何ですか?
ベストアンサー1
this
Bind は、関数の内部を に渡されるパラメータに強制する新しい関数を作成しますbind()
。
bind
以下は、正しい を持つメンバー メソッドを渡すために を使用する方法を示す例ですthis
。
var myButton = {
content: 'OK',
click() {
console.log(this.content + ' clicked');
}
};
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
次のように出力されます:
OK clicked
undefined clicked
OK clicked
最初の ( this
) パラメータの後にパラメータを追加して、bind
それらの値を元の関数に渡すこともできます。後でバインドされた関数に渡す追加のパラメータは、バインドされたパラメータの後に渡されます。
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
次のように出力されます:
15
チェックアウトJavaScript 関数バインド詳細情報とインタラクティブな例については、こちらをご覧ください。
更新: ECMAScript 2015 では=>
関数のサポートが追加されました。関数はよりコンパクトで、定義スコープからポインター=>
を変更しないため、それほど頻繁に使用する必要がないかもしれません。たとえば、最初の例の関数を使用してコールバックを DOM イベントに接続したい場合、以下はすべて有効な方法です。this
bind()
Button
click
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
または:
var myButton = {
... // As above
hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
};
または:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};