大网数据广告活动
Web 标准与前端开发

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

· 52CE 我爱测

在函数顶部直接写了 `"use strict"` ,而该函数拥有以下的参数其中之一:

信息

Firefox:
句法错误:"use strict" 不允许在带默认参数的函数中
句法错误:"use strict" 不允许在带 rest 参数的函数中
句法错误:"use strict" 不允许在带解构参数的函数中

Chrome:
句法错误:非法的'use strict'指令,在带有非简单参数列表的函数中

错误类型

SyntaxError.

哪里出错了?

在函数顶部直接写了 "use strict" ,而该函数拥有以下的参数其中之一:

  • Functions/Default_parameters
  • Functions/rest_parameters
  • Operators/Destructuring

根据 ECMAScript 规范,不允许在这些函数的顶部使用“use strict”指令。

示例

函数语句

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

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

如果这个函数应该处于 strict mode,并且整个脚本或封装函数也可以在严格模式下,可以移动 "use strict" 指令到函数之外:

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

函数表达式

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

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

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

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

箭头函数

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

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

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

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

参见

  • Strict_mode
  • Statements/function
  • Operators/function
  • Functions/Default_parameters
  • Functions/rest_parameters
  • Operators/Destructuring

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。