javascript this使用時にエラー「Uncaught TypeError: Cannot set property ‘xxx’ of undefined」が発生した場合

javascript this使用時にエラー「Uncaught TypeError: Cannot set property ‘xxx’ of undefined」が発生した場合

javascriptで、関数内で、アロー関数を使用時にthis使用時にエラー「Uncaught TypeError: Cannot set property ‘xxx’ of undefined」が発生した場合の原因と対処法。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.81

エラー内容

厳格モードで、以下のコードを実行するとエラーが発生します。

'use strict';

function hoge() {
  this.name = "mebee"
  console.log(this.name)
}

hoge();

エラー全文

// chrome 84
Uncaught TypeError: Cannot set property 'name' of undefined

// chrome 104
Uncaught TypeError: Cannot set properties of undefined (setting 'name')

firefox 102では以下のエラーとなります。

Uncaught TypeError: this is undefined

safari15.5では、以下のエラーとなります。

TypeError: undefined is not an object (evaluating 'this.name = "mebee"')

原因

関数は「this」を持っているため。

対処法

アロー関数は「this」を持たないので、アロー関数だと「this」を使用できます。

'use strict';

const hoge = () => {
  this.name = "mebee"
  console.log(this.name);
}

hoge(); // mebee