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

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

Edge:
Cannot apply strict mode on functions with non-simple parameter list

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

Error type

SyntaxError.

What went wrong?

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

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

Examples

Function statement

In this case, the function sum has default parameters a=1 and b=2:

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

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:

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

Function expression

A function expression can use yet another workaround:

var 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:

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

Arrow function

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

var 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:

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

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:120 次

字数:5154

最后编辑:6 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文