Understanding 'this' in JavaScript
Master the 'this' keyword and its binding in different contexts.

'this' in Different Contexts#
Global Context#
Code
console.log(this); // Window (browser) or global (Node.js)Function Context#
Code
function regularFunction() {
console.log(this); // Window (non-strict) or undefined (strict)
}
const obj = {
name: 'John',
greet: function() {
console.log(this.name); // 'John'
},
arrow: () => {
console.log(this); // Window (lexical this)
}
};Binding Methods#
Code
// call, apply, bind
const person = {
name: 'John'
};
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
greet.call(person, 'Hello'); // "Hello, John"
greet.apply(person, ['Hi']); // "Hi, John"
const boundGreet = greet.bind(person);
boundGreet('Hey'); // "Hey, John"