このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

SyntaxError: "use strict" not allowed in function with non-simple parameters

JavaScript の例外 ""use strict" not allowed in function" は、デフォルト引数、残余引数、構造分解引数を持つ関数の先頭で "use strict" ディレクティブを使用したときに発生します。

エラーメッセージ

SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list (V8-based)
SyntaxError: "use strict" not allowed in function with default parameter (Firefox)
SyntaxError: "use strict" not allowed in function with rest parameter (Firefox)
SyntaxError: "use strict" not allowed in function with destructuring parameter (Firefox)
SyntaxError: 'use strict' directive not allowed inside a function with a non-simple parameter list. (Safari)

エラー型

SyntaxError。

何がうまくいかなかったのか?

次の引数のいずれかを持つ関数の先頭に "use strict" ディレクティブが書かれています。

ECMAScript 仕様では、このような関数の先頭に "use strict" を使用することは許可されていません。

例

関数宣言

この例では、関数 sum はデフォルト引数 a=1 と b=2 を持っています。

js
function sum(a = 1, b = 2) {
  // SyntaxError: "use strict" not allowed in function with default parameter
  "use strict";
  return a + b;
}

関数を厳格モードにしたく、スクリプト全体または外側の関数も厳格モードになってよい場合は、"use strict" ディレクティブを関数の外側に移動できます。

js
"use strict";
function sum(a = 1, b = 2) {
  return a + b;
}

関数式

関数式では、別の回避策を使えます。

js
const sum = function sum([a, b]) {
  // SyntaxError: "use strict" not allowed in function with destructuring parameter
  "use strict";
  return a + b;
};

これは、次の式に変換できます。

js
const sum = (function () {
  "use strict";
  return function sum([a, b]) {
    return a + b;
  };
})();

アロー関数

アロー関数が this 変数にアクセスする必要がある場合、アロー関数を外側の関数として使用できます。

js
const callback = (...args) => {
  // SyntaxError: "use strict" not allowed in function with rest parameter
  "use strict";
  return this.run(args);
};

これは、次の式に変換できます。

js
const callback = (() => {
  "use strict";
  return (...args) => this.run(args);
})();

関連情報