🎯 Master the this Keyword
this is confusing. Understanding this is essential. Context, binding, arrow functions — master it.
📝 this in Different Contexts
// Global context
console.log(this); // Window (browser)
// Function context
function showThis() {
console.log(this); // Window (strict: undefined)
}
// Object method
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name); // 'Alice'
}
};
// Constructor function
function User(name) {
this.name = name;
}
const user = new User('Bob');
console.log(user.name); // 'Bob'
// Event handlers
button.addEventListener('click', function() {
console.log(this); // button element
});
// Arrow functions (lexical this)
const arrow = {
name: 'Charlie',
greet: () => {
console.log(this.name); // Window (not 'Charlie')
}
};
🎯 Binding this
// call() - call with specific this
function greet() {
console.log(`Hello ${this.name}`);
}
const person = { name: 'Alice' };
greet.call(person); // Hello Alice
// apply() - call with array arguments
function introduce(age, city) {
console.log(`${this.name} is ${age} from ${city}`);
}
introduce.apply(person, [30, 'NYC']);
// bind() - create new function with this bound
const boundGreet = greet.bind(person);
boundGreet(); // Hello Alice
// setTimeout with this
const timer = {
name: 'Timer',
start: function() {
// Bad: this is window
setTimeout(function() {
console.log(this.name); // undefined
}, 1000);
// Good: arrow function
setTimeout(() => {
console.log(this.name); // Timer
}, 1000);
}
};
// Class methods
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
greetArrow = () => {
console.log(`Hello ${this.name}`);
}
}
💡 this Tips
- Use arrow functions for lexical this
- Use bind() for event handlers
- Use call/apply for borrowing methods
- In classes, use arrow methods for callbacks
- this in strict mode is undefined
“Understanding this is essential. Context, binding, arrow functions. Essential for JavaScript mastery.”
