thisis a special keyword that refers to the execution context — the object that is currently calling or owning the code.- Its value depends on how the function is called, not where it's written.
thisis dynamic (changes with call style), except in arrow functions (lexical binding).
console.log(this);
// In browsers → window
// In Node (ESM) → undefined- In non-strict mode:
thisis the global object (windowin browsers). - In strict mode:
thisisundefined.
function showThis() {
console.log(this);
}
showThis(); // global object (non-strict) OR undefined (strict)const obj = {
name: 'John',
greet() {
console.log(this.name);
},
};
obj.greet(); // "John"Here, this refers to the object before the dot.
function Person(name) {
this.name = name;
}
const p = new Person('Alice');
console.log(p.name); // "Alice"With new, this refers to the newly created object.
const obj = {
value: 42,
arrow: () => console.log(this.value),
};
obj.arrow(); // undefined- Arrow functions do not have their own
this. - They inherit
thisfrom the lexical scope where they were defined.
document.querySelector('button').addEventListener('click', function () {
console.log(this); // The button element
});In a DOM event handler, this refers to the element that received the event (unless using an arrow function).
function greet(city) {
console.log(`Hello ${this.name} from ${city}`);
}
const user = { name: 'Bob' };
greet.call(user, 'Paris'); // Hello Bob from Paris
greet.apply(user, ['London']); // Hello Bob from London
const boundGreet = greet.bind(user, 'Rome');
boundGreet(); // Hello Bob from Rome- call → invoke immediately, pass arguments individually.
- apply → invoke immediately, pass arguments as array.
- bind → returns a new function with bound
this.
const obj = {
name: 'Sam',
greet() {
setTimeout(function () {
console.log(this.name); // undefined
}, 1000);
},
};
obj.greet();Fix: Use arrow functions or .bind(this):
setTimeout(() => console.log(this.name), 1000);When multiple rules apply, priority order:
- new binding (constructor) → highest priority
- Explicit binding (call, apply, bind)
- Implicit binding (object method call)
- Default binding (global object or undefined in strict mode)
- Arrow functions → ignore all above, use lexical scope
-
What does
thisrefer to in the global scope in strict mode vs non-strict mode? -
How does
thisbehave inside arrow functions vs normal functions? -
What's the output of:
const obj = { a: 10, b: () => console.log(this.a), }; obj.b();
-
How do
call,apply, andbindaffectthis? -
What happens to
thiswhen you extract a method from an object and call it standalone? -
How does
thiswork in event handlers?