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);
})();