Understanding this
in JavaScript
The this
keyword refers to the object it belongs to. It behaves differently depending on how a function is called.
🔍 Global Context
console.log(this);
// In browsers, this refers to the global window object
📦 Inside an Object Method
const user = {
name: "Alice",
greet: function() {
console.log("Hi, I'm " + this.name);
}
};
user.greet(); // "Hi, I'm Alice"
⚠️ In a Regular Function
function show() {
console.log(this);
}
show();
// In strict mode: undefined
// Otherwise: window (in browser)
⚡ With Arrow Functions
Arrow functions do not bind their own this
. They inherit it from the outer lexical scope.
const person = {
name: "Bob",
greet: () => {
console.log("Hi, I'm " + this.name);
}
};
person.greet(); // "Hi, I'm undefined"
🧠 Using bind()
, call()
, and apply()
function sayHello() {
console.log("Hello, " + this.name);
}
const person = { name: "Charlie" };
sayHello.call(person); // Hello, Charlie
sayHello.apply(person); // Hello, Charlie
const boundFunc = sayHello.bind(person);
boundFunc(); // Hello, Charlie
💡 Tip: Always be mindful of how a function is called — that's what determines what
this
refers to.