The handling of “this” is also different in arrow functions compared to regular functions.
In short, with arrow functions there are no binding of “this”.
In regular functions the “this” keyword represented the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions the “this” keyword always represents the object that defined the arrow function.
Let us take a look at two examples to understand the difference.
Both examples call a method twice, first when the page loads, and once again when the user clicks a button.
The first example uses a regular function, and the second example uses an arrow function.
The result shows that the first example returns two different objects (window and button), and the second example returns the window object twice, because the window object is the “owner” of the function.
Example 2:
With a regular function “this” represents the object that “calls” the function:
<body>
<h2>JavaScript "this"</h2>
<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>
var 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>
//Output :
[object Window][object HTMLButtonElement][object HTMLButtonElement]
Example 2 :
With an arrow function “this” represents the “owner” of the function:
<body>
<h2>JavaScript "this"</h2>
<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>
var 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>
//Output :
[object Window][object Window][object Window][object Window]