语法错误:"使用严格" 不允许出现在具有非简单参数的函数中

当在具有 default parametersrest parametersdestructuring parameters 的函数顶部使用 "use strict" 指令时,会出现 JavaScript 异常“函数中不允许使用 "use strict"”。

¥The JavaScript exception ""use strict" not allowed in function" occurs when a "use strict" directive is used at the top of a function with default parameters, rest parameters, or destructuring parameters.

信息

¥Message

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)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

"use strict" 伪指令写在具有以下参数之一的函数的顶部:

¥A "use strict" directive is written at the top of a function that has one of the following parameters:

根据 ECMAScript 规范,此类函数的顶部不允许使用 "use strict" 指令。

¥A "use strict" directive is not allowed at the top of such functions per the ECMAScript specification.

示例

¥Examples

函数声明

¥Function statement

在这种情况下,函数 sum 有默认参数 a=1b=2

¥In this case, the function sum has default parameters a=1 and 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" 指令移到函数之外:

¥If the function should be in strict mode, and the entire script or enclosing function is also okay to be in strict mode, you can move the "use strict" directive outside of the function:

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

函数表达式

¥Function expression

函数表达式可以使用另一种解决方法:

¥A function expression can use yet another workaround:

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

这可以转换为以下表达式:

¥This can be converted to the following expression:

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

箭头函数

¥Arrow function

如果箭头函数需要访问 this 变量,可以使用箭头函数作为封闭函数:

¥If an arrow function needs to access the this variable, you can use the arrow function as the enclosing function:

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

这可以转换为以下表达式:

¥This can be converted to the following expression:

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

也可以看看