javascript エラー「TypeError: |this| is not a function inside Function.prototype.bind」の解決方法

javascript エラー「TypeError: |this| is not a function inside Function.prototype.bind」の解決方法

javascriptで、エラー「TypeError: |this| is not a function inside Function.prototype.bind」が発生した場合の原因と解決方法を記述してます。

環境

  • OS macOS Big Sur
  • ブラウザ safari 15.0

エラー内容

以下のコードを実行した際に発生。

const obj = {    
    fn:function (){ console.log(this);}
}

const arr = [0, 1]

console.log(
  arr.forEach(obj.fn.bind)
)

エラーメッセージ

TypeError: |this| is not a function inside Function.prototype.bind

画像

原因

関数の括弧がないため

解決方法

括弧を使う

const obj = {    
    fn:function (){ console.log(this);}
}

const arr = [0, 1]

console.log(
  arr.forEach(obj.fn.bind())
)

実行結果