SyntaxError: "use strict" not allowed in function with non-simple parameters
Fehlermeldung
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
Fehlertyp
Was ist falsch gelaufen?
Eine "use strict"
Direktive steht am Anfang einer Funktion, die einen der folgende Parameter hat:
Eine "use strict"
Direktive ist am Anfang solcher Funktionen durch die ECMAScript Spezifikation nicht erlaubt.
Beispiele
Funktionsstatement
In diesem Fall hat die Funktion sum
zwei Standardparameter a=1
und b=2
:
function sum(a = 1, b = 2) {
// SyntaxError: "use strict" not allowed in function with default parameter
'use strict';
return a + b;
}
Wenn die Funktion im Strict Mode sein soll und das Skript oder die umschließende FUnktion auch für den Strict Mode in Ordnung ist, kann man die "use strict"
Direktive nach außen verschieben:
'use strict';
function sum(a = 1, b = 2) {
return a + b;
}
Funktionsausdruck
Bei eine Funktionsausdruck kann ein andere Workaround genutzt werden:
var sum = function sum([a, b]) {
// SyntaxError: "use strict" not allowed in function with destructuring parameter
'use strict';
return a + b;
};
Dieses kann zu folgendem Ausdruck konvertiert werden:
var sum = (function() {
'use strict';
return function sum([a, b]) {
return a + b;
};
})();
Pfeilfunktionen
Wenn eine Pfeilfunktion auf die this
Variable zugreift, so kann eine umschließende Pfeilfunktion benutzt werden:
var callback = (...args) => {
// SyntaxError: "use strict" not allowed in function with rest parameter
'use strict';
return this.run(args);
};
Dieses kann zu folgendem Ausdruck konvertiert werden:
var callback = (() => {
'use strict';
return (...args) => {
return this.run(args);
};
})();