← 返回首页
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript | MDN

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

View in English Always switch to English

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

メッセージ

Firefox: SyntaxError: "use strict" not allowed in function with default parameter SyntaxError: "use strict" not allowed in function with rest parameter SyntaxError: "use strict" not allowed in function with destructuring parameter Chrome: SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list

In this article

エラーの種類

SyntaxError

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

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

ECMAScript 仕様に則って、このような関数の先頭では "use strict" を使用できません。

Function ステートメント

このケースでは、関数 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; }

関数を strict モードにしたい、かつスクリプト全体、またはエンクロージャー関数が strict モードになってもよいなら、"use strict" ディレクティブを関数の外側に移動できます:

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

Function 式

function 式では、別の回避策をとることができます:

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

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

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

アロー関数

アロー関数が this 変数にアクセスする必要がある場合、アロー関数をエンクロージャー関数として使用できます:

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

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

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

関連情報