Fonction de flèche JavaScript


Table des matières

    Afficher la table des matières

Les fonctions fléchées ont été introduites dans ES6.

Les fonctions fléchées nous permettent d'écrire une syntaxe de fonction plus courte :

let myFunction = (a, b) => a * b;

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>

<p>This example shows the syntax of an Arrow Function, and how to use it.</p>

<p id="demo"></p>

<script>
let myFunction = (a, b) => a * b;
document.getElementById("demo").innerHTML = myFunction(4, 5);
</script>

</body>
</html>

Avant la flèche :

hello = function() {
  return "Hello World!";
}

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>This example shows the syntax of a function, without the use of arrow function syntax.</p>

<p id="demo"></p>

<script>
let hello = "";

hello = function() {
  return "Hello World!";
}

document.getElementById("demo").innerHTML = hello();
</script>

</body>
</html>

Avec fonction flèche :

hello = () => {
  return "Hello World!";
}

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>

<p>This example shows the syntax of an Arrow Function, and how to use it.</p>

<p id="demo"></p>

<script>
let hello = "";

hello = () => {
  return "Hello World!";
}

document.getElementById("demo").innerHTML = hello();
</script>

</body>
</html>

Ça devient plus court ! Si la fonction n'a qu'une seule instruction et que l'instruction renvoie une valeur, vous pouvez supprimer les crochets et le Mot-clé return :

Les fonctions fléchées renvoient la valeur par défaut :

hello = () => "Hello World!";

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>

<p>This example shows an Arrow Function without the brackets or the return keyword.</p>

<p id="demo"></p>

<script>
let hello = "";

hello = () => "Hello World!";

document.getElementById("demo").innerHTML = hello();
</script>

</body>
</html>

Remarque : Cela ne fonctionne que si la fonction n'a qu'un seul déclaration.

Si vous avez des paramètres, vous les transmettez entre parenthèses :

Fonction flèche avec paramètres :

hello = (val) => "Hello " + val;

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>

<p>This example shows an Arrow Function with a parameter.</p>

<p id="demo"></p>

<script>
let hello = "";

hello = (val) => "Hello " + val;

document.getElementById("demo").innerHTML = hello("Universe!");
</script>

</body>
</html>

En fait, si vous n’avez qu’un seul paramètre, vous pouvez également ignorer les parenthèses :

Fonction flèche sans parenthèses :

hello = val => "Hello " + val;

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>

<p>This example shows that if you have only one parameter in an Arrow Function, you can skip the parentheses.</p>

<p id="demo"></p>

<script>
let hello = "";

hello = val => "Hello " + val;

document.getElementById("demo").innerHTML = hello("Universe!");
</script>

</body>
</html>


Qu'en est-il de ce ?

La gestion de this est également différente dans les fonctions fléchées par rapport aux fonctions normales. les fonctions.

En bref, avec les fonctions fléchées, il n'y a pas de liaison de ce.

Dans les fonctions régulières, le mot-clé this représentait l'objet qui appelait le fonction, qui peut être la fenêtre, le document, un bouton ou autre.

Avec les fonctions fléchées, le mot clé this toujours représente le objecter que défini la fonction de flèche.

Jetons un coup d'œil à deux exemples pour comprendre la différence.

Les deux exemples appellent une méthode deux fois, d'abord au chargement de la page, puis de nouveau lorsque l'utilisateur clique sur un bouton.

Le premier exemple utilise une fonction régulière et le deuxième exemple utilise un fonction flèche.

Le résultat montre que le premier exemple renvoie deux objets différents (fenêtre et bouton), et le Le deuxième exemple renvoie l'objet window deux fois, car l'objet window est le "propriétaire" de la fonction.

Exemple

Avec une fonction régulière ce représente le objet qui appelle la fonction :

 // Regular Function:
hello = function() {
  document.getElementById("demo").innerHTML 
  += this;
}
// The window object calls the function:
  window.addEventListener("load", hello);
// A button object calls the 
  function:
document.getElementById("btn").addEventListener("click", hello);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript "this"</h1>

<p>This example demonstrate that in a regular function, the "this" keyword represents different objects depending on how the function was called.</p>

<p>Click the button to execute the "hello" function again, and you will see that this time "this" represents the button object.</p>

<button id="btn">Click Me!</button>

<p id="demo"></p>

<script>
let hello = "";

hello = function() {
  document.getElementById("demo").innerHTML += this;
}

//The window object calls the function:
window.addEventListener("load", hello);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>

</body>
</html>

Exemple

Avec une fonction flèche ce représente le propriétaire de la fonction :

 // Arrow Function:
hello = () => {
  document.getElementById("demo").innerHTML 
  += this;
}
// The window object calls the function:
  window.addEventListener("load", hello);
// A button object calls the 
  function:
document.getElementById("btn").addEventListener("click", hello);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript "this"</h1>

<p>This example demonstrate that in Arrow Functions, the "this" keyword represents the object that owns the function, no matter who calls the function.</p>

<p>Click the button to execute the "hello" function again, and you will see that "this" still  represents the window object.</p>

<button id="btn">Click Me!</button>

<p id="demo"></p>

<script>
let hello = "";

hello = () => {
  document.getElementById("demo").innerHTML += this;
}

//The window object calls the function:
window.addEventListener("load", hello);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>

</body>
</html>

N'oubliez pas ces différences lorsque vous travaillez avec des fonctions. Parfois l le comportement des fonctions régulières est ce que vous voulez, sinon, utilisez les fonctions fléchées.


Prise en charge du navigateur

Le tableau suivant définit les premières versions du navigateur avec une prise en charge complète de Fonctions fléchées en JavaScript :

Chrome 45 Edge 12 Firefox 22 Safari 10 Opera 32
Sep, 2015 Jul, 2015 May, 2013 Sep, 2016 Sep, 2015