The this Keyword
The this keyword is consistently ranked among the top interview topics and trips up even experienced developers.
How this is Determined
The value of this is NOT set when a function is defined — it is set based on how the function is called.
| Context | this value |
|---|---|
| Global (non-strict) | window/global |
| Global (strict) | undefined |
| Object method | The object |
| Arrow function | Enclosing scope's this |
| new constructor | New instance |
| call/apply/bind | Explicitly provided |
const obj = {
name: 'Alice',
greet() {
console.log(this.name); // 'Alice'
},
greetArrow: () => {
console.log(this.name); // undefined (global this)
}
};
obj.greet();
obj.greetArrow();
call, apply, and bind
function greet(greeting, punct) {
return greeting + ', ' + this.name + punct;
}
const user = { name: 'Bob' };
greet.call(user, 'Hello', '!'); // Hello, Bob!
greet.apply(user, ['Hello', '!']); // Hello, Bob!
const boundGreet = greet.bind(user);
boundGreet('Hi', '.'); // Hi, Bob.