Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is lexical this in JavaScript?
In JavaScript, "lexical this" refers to how arrow functions inherit the this context from their enclosing scope, unlike regular functions that define their own this. This solves common issues with this binding in callbacks and nested functions.
The Problem with Regular Functions
Regular functions create their own this context, which can lead to unexpected behavior in callbacks:
<button id="myButton">Click Me</button>
<script>
document.getElementById('myButton').addEventListener('click', function() {
console.log('Outer this:', this); // Points to the button
setTimeout(function() {
console.log('Inner this:', this); // Points to window (global object)
this.textContent = 'Changed'; // Won't work as expected
}, 1000);
});
</script>
Solution: Arrow Functions with Lexical this
Arrow functions don't have their own this ? they inherit it from the surrounding scope:
<button id="myButton2">Click Me</button>
<script>
document.getElementById('myButton2').addEventListener('click', function() {
console.log('Outer this:', this); // Points to the button
setTimeout(() => {
console.log('Inner this:', this); // Still points to the button
this.textContent = 'Changed Successfully'; // Works correctly
}, 1000);
});
</script>
Key Differences
| Function Type | Has Own this? | this Value |
|---|---|---|
| Regular Function | Yes | Depends on how it's called |
| Arrow Function | No | Inherited from enclosing scope |
Practical Example
const obj = {
name: 'JavaScript Object',
regularMethod: function() {
console.log('Regular:', this.name);
// Problem: this changes in callback
setTimeout(function() {
console.log('Regular callback:', this.name); // undefined
}, 100);
// Solution: arrow function preserves this
setTimeout(() => {
console.log('Arrow callback:', this.name); // 'JavaScript Object'
}, 200);
}
};
obj.regularMethod();
Regular: JavaScript Object Regular callback: undefined Arrow callback: JavaScript Object
Conclusion
Arrow functions provide lexical this binding, inheriting the this value from their enclosing scope. This eliminates the need for .bind() or storing this in variables when working with callbacks and event handlers.
Advertisements
