Home Courses This keyword with Arrow Function vs Normal Function

This keyword with Arrow Function vs Normal Function

What is this keyword?

  1. this refers to the current object.
  2. It provides reference to the object in which it is used.
  3. Its value depends on how and where the function is called.


this in Normal Function (Object Method)

Example:


<script>
let userData = {
userName: "anil sidhu",

getName: function () {
console.log(this.userName);
}
}

userData.getName();
</script>

Output:

anil sidhu

Explanation:

  1. this refers to the current object (userData).
  2. So this.userName means userData.userName.


this in Arrow Function (Important Concept)

Example:


<script>
const userData = {
userName: "anil sidhu",

getName: () => {
console.log(this.userName);
}
}

userData.getName();
</script>

Output:

undefined

Why?

  1. Arrow functions do not have their own this.
  2. They take this from the parent lexical scope.
  3. Here, parent scope is global, so this.userName is undefined.


Lexical Scope in Arrow Function

  1. Arrow functions inherit this from the outer scope.
  2. They do not create their own this.

Summary:

  1. Arrow function → uses parent this
  2. Normal function → uses its own object this


Problem Example with setTimeout

Code:


<script>
const userData = {
userName: "anil sidhu",

print: function () {
setTimeout(function () {
console.log(this.userName);
}, 0);
}
}

userData.print();
</script>

Output:

undefined

Reason:

  1. setTimeout creates its own execution context.
  2. this no longer refers to userData.


Solution: Use Arrow Function

Correct Code:


<script>
const userData = {
userName: "anil sidhu",

print: function () {
setTimeout(() => {
console.log(this.userName);
}, 0);
}
}

userData.print();
</script>

Output:

anil sidhu


Why Arrow Function Works Here?

  1. Arrow function does not have its own this.
  2. It uses this from the print() function.
  3. print() belongs to userData, so this.userName works correctly.


Share this lesson: