this
?The behavior of this
differs between arrow functions and regular functions.
In summary, arrow functions do not bind this
.
In regular functions, this
refers to the object that called the function, which could be the window
, document
, a button, or any other object.
In contrast, with arrow functions, this
always refers to the object where the arrow function was defined.
Let’s consider two examples to see the difference. Both examples invoke a method twice: once when the page loads, and once again when the user clicks a button.
The first example uses a regular function, and the second uses an arrow function.
The result demonstrates that in the first example, this
refers to two different objects (the window
and the button
), whereas in the second example, this
refers to the window
object in both cases, since the window
object is the “owner” of the arrow function.
In a regular function, this
refers to the object that invokes the function.
// 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); |
In an arrow function, this
refers to the object that defines the function.
// 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); |
Keep these differences in mind when working with functions. If the behavior of regular functions is what you need, use them; otherwise, opt for arrow functions.
The following table lists the first browser versions that fully support arrow functions in JavaScript: