Curriculum
Course: React
Login

Curriculum

React

Text lesson

What About this ?

The handling of this differs between arrow functions and regular functions.

In regular functions, this refers to the object that invoked the function (e.g., windowdocument, or a button), whereas in arrow functions, this always refers to the object where the arrow function was defined.

For example, when a method is called twice—once on page load and once on button click—the regular function returns different objects (window and button), while the arrow function consistently returns the same object (Header).

Example

In a regular function, this refers to the object that invoked the function.

class Header {
 constructor() {
    this.color = "Red";
  }
//Regular function:
 changeColor = function() {
    document.getElementById("demo").innerHTML += this;
 }
}
const myheader = new Header();
//The window object calls the function:
window.addEventListener("load", myheader.changeColor);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);

Example

In an arrow function, this always refers to the Header object, regardless of who called the function.

class Header {
 constructor() {
    this.color = "Red";
 }
//Arrow function:
 changeColor = () => {
    document.getElementById("demo").innerHTML += this;
 }
}
const myheader = new Header();
//The window object calls the function:
window.addEventListener("load", myheader.changeColor);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);