javascript エラー「Uncaught TypeError: Object prototype may only be an Object or null: undefined」の解決方法

javascript エラー「Uncaught TypeError: Object prototype may only be an Object or null: undefined」の解決方法

javascriptで、エラー「Uncaught TypeError: Object prototype may only be an Object or null: undefined」が発生した場合の原因と解決方法を記述してます。「Object.create()」で引数を指定せずに実行している場合に発生します。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.125

エラー内容

以下のコードで発生。

let obj = Object.create();

エラーメッセージ

Uncaught TypeError: Object prototype may only be an Object or null: undefined

画像

firefox(バージョン107)では、以下のエラーとなります。

Uncaught TypeError: Object.create: At least 1 argument required, but only 0 passed

画像

safari(15.5)だと、以下のエラーが発生します。

TypeError: Object prototype may only be an Object or null.

画像

原因

「Object.create()」は、引数が必須なため引数を指定していないとエラーとなります。

解決方法

引数を指定するか、「null」を引数に渡す

let foo = { 'a': { 'b': 2 } };

let obj = Object.create(foo);

or

let obj = Object.create(null);