[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Errors/Strict_non_simple_params [Back]  [Original]

SyntaxError: "use strict" not allowed in function with "x" parameter - JavaScript | MDN

Cette page a t traduite partir de l'anglais par la communaut. Vous pouvez contribuer en rejoignant la communaut francophone sur MDN Web Docs.

View in English Always switch to English

SyntaxError: "use strict" not allowed in function with "x" parameter

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

Dans cet article

Type d'erreur

SyntaxError.

Quel est le problme ?

Une directive "use strict" apparat au dbut d'une fonction qui possde l'un des paramtres suivants :

Selon la spcification ECMAScript, une directive "use strict" ne peut pas tre utilise pour de telles fonctions.

Exemples

Dclaration de fonction

Dans l'exemple qui suit, la fonction somme possde deux paramtres par dfaut a=1 et b=2.

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

Si on veut que la fonction soit en mode strict et que le script entier ou que la fonction englobante peut tre en mode strict, il suffira de dplacer l'instruction "use strict" en dehors du corps de la mthode.

js
"use strict";
function somme(a = 1, b = 2) {
  return a + b;
}

Expression de fonction

Il est galement possible d'utiliser les expressions de fonction pour rsoudre ce problme :

js
var somme = function somme([a, b]) {
  // SyntaxError: "use strict" not allowed in function with destructuring parameter
  "use strict";
  return a + b;
};

On peut convertir le fragment de code prcdent avec l'expression suivante :

js
var somme = (function () {
  "use strict";
  return function somme([a, b]) {
    return a + b;
  };
})();

Fonction flche

Si on a une fonction flche qui doit accder la variable this on peut utiliser une fonction flche comme fonction englobante :

js
var callback = (...args) => {
  // SyntaxError: "use strict" not allowed in function with rest parameter
  "use strict";
  return this.run(args);
};

This can be converted into following expression.

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

Voir aussi


Web Proxy Viewer  |  New URL  |  Original Page