By Hemanta Sundaray on 2022-04-19
We know that when we use the this keyword in a method, then the value of this is the calling object.
The calling object is the object the method belongs to.
However, it becomes a bit more complicated when we start using arrow functions for methods.
const rover = {
name: "Perseverance",
job: () => {
console.log(`${this.name} will seek signs of ancient life on Mars.`)
},
}
console.log(rover.job())
// undefined
In the example above, notice that we have defined the job() method using an arrow function.
Also, notice that console.log(rover.job()) logs undefined.
What happened?
Arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object. In the code snippet above, the value of this is the global object, or an object that exists in the global scope, which doesn’t have a name property and therefore returns undefined.
The key takeaway from the example above is to avoid using arrow functions when using this in a method!