This keyword with Arrow Function vs Normal Function
What is this keyword?
thisrefers to the current object.- It provides reference to the object in which it is used.
- 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:
thisrefers to the current object (userData).- So
this.userNamemeansuserData.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?
- Arrow functions do not have their own
this. - They take
thisfrom the parent lexical scope. - Here, parent scope is global, so
this.userNameis undefined.
Lexical Scope in Arrow Function
- Arrow functions inherit
thisfrom the outer scope. - They do not create their own
this.
Summary:
- Arrow function → uses parent
this - 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:
setTimeoutcreates its own execution context.thisno longer refers touserData.
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?
- Arrow function does not have its own
this. - It uses
thisfrom theprint()function. print()belongs touserData, sothis.userNameworks correctly.