SyntaxError: "use strict" not allowed in function with non-simple parameters
当一个函数顶部使用了 "use strict" 指令,而该函数拥有默认参数、剩余参数或解构参数时,会抛出 JavaScript 异常 “"use strict" not allowed in function”。
消息
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)
错误类型
哪里出错了?
"use strict" 指令写在具有以下参数之一的函数顶部:
根据 ECMAScript 规范,此种函数顶部不允许使用 "use strict" 指令。
示例
函数声明
在此示例中,函数 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;
}
如果函数应该处于严格模式,并且整个脚本或包含函数也都可以处于严格模式,你可以将 "use strict" 指令移到函数外部
js
"use strict";
function sum(a = 1, b = 2) {
return a + b;
}
函数表达式
函数表达式可以使用另一种变通方法
js
const sum = function sum([a, b]) {
// SyntaxError: "use strict" not allowed in function with destructuring parameter
"use strict";
return a + b;
};
这可以转换为以下表达式
js
const sum = (function () {
"use strict";
return function sum([a, b]) {
return a + b;
};
})();
箭头函数
如果箭头函数需要访问 this 变量,你可以将箭头函数用作包含函数
js
const callback = (...args) => {
// SyntaxError: "use strict" not allowed in function with rest parameter
"use strict";
return this.run(args);
};
这可以转换为以下表达式
js
const callback = (() => {
"use strict";
return (...args) => this.run(args);
})();