bindメソッドを使ってthisを指定する
変数にオブジェクトのメソッドを代入した場合、thisキーワードがあると正しく動作しません。
正しく動作するケース
次のようなソースコードの場合は問題なく動作します。
const object = {
name: "obj",
showName: function() {
return this.name;
}
};
const insertObject = object;
console.log(insertObject.showName());
実行結果
obj
当然ですが、こちらも。
const object = {
name: "obj",
showName: function() {
return "obj";
}
};
const unboundFunc = object.showName;
console.log(unboundFunc());
実行結果
obj
this キーワードあり
thisキーワードがあるメソッドを代入すると動作しません。
const object = {
name: "obj",
showName: function() {
return this.name;
}
};
const unboundFunc = object.showName;
console.log(unboundFunc());
実行結果
undefined
bind() を使って this を指定する
bind()メソッドを使いthisとなるオブジェクトを指定します。戻り値はthisを反映した関数のコピーなのでそちらを実行します。
const object = {
name: "obj",
showName: function() {
return this.name;
}
};
const unboundFunc = object.showName;
const boundFunc = unboundFunc.bind(object);
console.log(boundFunc());
実行結果
obj
別のオブジェクトを指定することもできます。
const object = {
name: "obj",
showName: function() {
return this.name;
}
};
const object2 = {
name: "obj2",
}
const unboundFunc = object.showName;
const boundFunc = unboundFunc.bind(object2);
実行結果
obj2
こういった使い方もできます。
const object2 = {
name: "obj2",
}
function showName() {
return this.name;
}
const unboundFunc = showName;
console.log(unboundFunc());
const boundFunc = unboundFunc.bind(object2);
console.log(boundFunc());
実行結果
undefined
obj2
bind()よりは代入したメソッドの動きを知っておかないとエラーで困りそうですね。
