首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Errors: Strict Non Simple Params

信息

代码语言:javascript
复制
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

错误类型

SyntaxError.

哪里出错了?

一个"use strict"指令是在具有下列参数之一的函数的顶部写:

  • 默认参数
  • 休息参数
  • 解构参数

根据"use strict"ECMAScript规范,在这些函数的顶部不允许有指令。

示例

函数声明

在这种情况下,该功能sum具有默认参数a=1b=2

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

如果函数应该处于严格模式,并且整个脚本或函数也可以处于严格模式,那么可以将该"use strict"指令移动到函数之外:

代码语言:javascript
复制
'use strict';
function sum(a = 1, b = 2) {
  return a + b;
}

函数表达式

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

代码语言:javascript
复制
var sum = function sum([a, b]) {
  // SyntaxError: "use strict" not allowed in function with destructuring parameter
  'use strict';
  return a + b;
};

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

代码语言:javascript
复制
var sum = (function() {
  'use strict';
  return function sum([a, b]) {
    return a + b;
  };
})();

箭头功能

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

代码语言:javascript
复制
var callback = (...args) => {
  // SyntaxError: "use strict" not allowed in function with rest parameter
  'use strict';
  return this.run(args);
};

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

代码语言:javascript
复制
var callback = (() => {
  'use strict';
  return (...args) => {
    return this.run(args);
  };
})();

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com