javascript bindを使ってオブジェクト内のthisを紐付けする

環境
Windows 10 Home 64bit
Google Chrome 109.0.5414.120(Official Build) (64 ビット)

構文
bind(thisArg)
引数
thisArg
バインド済み関数が呼び出される際、 this 引数としてターゲット関数 func に渡される値です
arg1, …, argN
func を呼び出す時、バインド済み関数に与えられる引数の前に付けて渡す引数。

戻り値
this の値と初期の引数(提供された場合)が指定された関数のコピーです。

使用例

const obj = {
    age:20,
    fn:function (){console.log(this)}
}

obj.fn() // オブジェクト内のthisが表示される

const res = obj.fn.bind(obj)

res()

実行結果
> Object { age: 20, fn: function (){console.log(this)} }
> Object { age: 20, fn: function (){console.log(this)} }

JavaScript

Posted by arkgame