Función de flecha de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos

Las funciones de flecha se introdujeron en ES6.

Las funciones de flecha nos permiten escribir una sintaxis de función más corta:

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

Pruébelo usted mismo →

<!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>

Antes de Flecha:

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

Pruébelo usted mismo →

<!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>

Con función de flecha:

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

Pruébelo usted mismo →

<!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>

¡Se hace más corto! Si la función tiene solo una declaración y la declaración devuelve un valor, puede eliminar los corchetes y el retorno palabra clave:

Valor de retorno de las funciones de flecha de forma predeterminada:

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

Pruébelo usted mismo →

<!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>

Nota: Esto funciona solo si la función tiene solo un declaración.

Si tienes parámetros, los pasas entre paréntesis:

Función de flecha con parámetros:

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

Pruébelo usted mismo →

<!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>

De hecho, si solo tiene un parámetro, también puede omitir los paréntesis:

Función de flecha sin paréntesis:

hello = val => "Hello " + val;

Pruébelo usted mismo →

<!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é pasa con este?

El manejo de this también es diferente en las funciones de flecha en comparación con las funciones normales. funciones.

En resumen, con las funciones de flecha no hay vinculación de este.

En funciones regulares, la palabra clave this representaba el objeto que llamaba al función, que podría ser la ventana, el documento, un botón o lo que sea.

Con funciones de flecha, la palabra clave this siempre representa la objetar que definió la función de flecha.

Echemos un vistazo a dos ejemplos para comprender la diferencia.

Ambos ejemplos llaman a un método dos veces, primero cuando se carga la página y otra vez. cuando el usuario hace clic en un botón.

El primer ejemplo usa una función regular y el segundo ejemplo usa una función de flecha.

El resultado muestra que el primer ejemplo devuelve dos objetos diferentes (ventana y botón), y el El segundo ejemplo devuelve el objeto de ventana dos veces, porque el objeto de ventana es el "propietario" de la función.

Ejemplo

Con una función normal esto representa el objeto que llama a la función:

 // 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);

Pruébelo usted mismo →

<!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>

Ejemplo

Con una función de flecha esto representa el propietario de la función:

 // 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);

Pruébelo usted mismo →

<!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>

Recuerde estas diferencias cuando trabaje con funciones. A veces el El comportamiento de las funciones regulares es lo que desea; si no, utilice funciones de flecha.


Soporte del navegador

La siguiente tabla define las primeras versiones del navegador con soporte completo para Funciones de flecha en JavaScript:

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