JavaScript
Quick reference for JavaScript syntax, methods, and common patterns.
🔍
Advanced JavaScript
Advanced JavaScript concepts including this binding, arrow functions, and more.
This Binding & Arrow Functions
How 'this' Works
Understanding the contextual nature of 'this'
// 'this' refers to the context where a function is called
const obj = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name);
}
};
obj.greet(); // 'this' refers to obj, outputs: "Hello, John"
const greetFunc = obj.greet;
greetFunc(); // 'this' refers to global/window, outputs: "Hello, undefined"Common Pitfalls
Common scenarios where 'this' binding is lost
// Pitfall 1: Method passed as callback
const obj = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name);
}
};
// 'this' loses context when passed as callback
setTimeout(obj.greet, 1000); // 'this' is global/window
// Pitfall 2: Nested functions
const obj2 = {
name: 'John',
greet: function() {
function innerGreet() {
console.log('Hello, ' + this.name); // 'this' is global/window
}
innerGreet();
}
};Arrow Functions Fix 'this'
How arrow functions solve 'this' binding issues
// Arrow functions inherit 'this' from surrounding scope
const obj = {
name: 'John',
greet: function() {
// Arrow function inherits 'this' from greet method
setTimeout(() => {
console.log('Hello, ' + this.name); // 'this' refers to obj
}, 1000);
}
};
// Arrow functions in class methods
class Person {
constructor(name) {
this.name = name;
}
greet = () => {
console.log('Hello, ' + this.name); // 'this' always refers to instance
}
}
const person = new Person('John');
const greetFunc = person.greet;
greetFunc(); // Still works! 'this' refers to personWhen to Use Each
Guidelines for choosing between regular and arrow functions
// Use regular functions when:
// 1. You need 'this' to be dynamic
// 2. Defining object methods
// 3. Using 'arguments' object
// 4. Need to be used as constructors
const obj = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name);
}
};
// Use arrow functions when:
// 1. You want to preserve 'this' context
// 2. Short, simple functions
// 3. Callbacks that need to access outer scope
// 4. Don't need 'this' or 'arguments'
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // Simple transformation
// Mix both approaches
class Calculator {
constructor() {
this.value = 0;
}
add = (num) => { // Arrow function preserves 'this'
this.value += num;
return this;
}
getValue() { // Regular function for method
return this.value;
}
}