JavaScript · Lesson 10 of 20 · 3 min
`this` Keyword and Context
This isn't an academic exercise. Getting this wrong in an interview signals a weak grasp of JavaScript's runtime model.
The value of this is determined by how a function is called, not where it is defined. This is called the "call-site". If you can find the call-site, you can determine this.
There is a clear hierarchy of rules. To find the value of this, you check these rules in order.
The Four Binding Rules, in Order of Precedence
-
newBinding: If a function is called with thenewkeyword (const c = new Car()),thisinside that function is the newly created object. This rule wins over all others. -
Explicit Binding: You can force
thisto be a specific object usingcall,apply, orbind.fn.call(thisArg, arg1, arg2): Callsfnimmediately withthisset tothisArg.fn.apply(thisArg, [arg1, arg2]): Same ascall, but takes arguments as an array.fn.bind(thisArg): Does not call the function. It returns a new function wherethisis permanently locked tothisArg. This is what you use for callbacks and event handlers.
-
Implicit Binding: When you call a function as a method of an object (
obj.method()),thisis the object to the left of the dot (obj).The classic trap: The context is lost if you pass the method without calling it.
setTimeout(obj.method, 1000)detachesmethodfromobj. WhensetTimeout's internals eventually invoke it, the call-site is justmethod(), which falls through to the default binding rule. -
Default Binding: If none of the other rules apply (a plain function call like
myFunction()),thisis the global object (windowin browsers). However, in strict mode,thisisundefined. Modern JavaScript (modules, classes) runs in strict mode by default, so you should almost always assumethiswill beundefined.
The Exception: Arrow Functions are Lexical
Arrow functions do not have their own this context. They ignore all four rules above.
Instead, this is resolved lexically, just like any other variable. It takes the value of this from its surrounding scope at the time it is defined. This makes them ideal for callbacks inside methods, as they automatically capture the correct this from the parent scope.
The trap: Do not use an arrow function for an object method if you need this to refer to the object itself. The arrow function will capture this from the scope where the object is defined (often the global scope), not from the object at call time.
Code Walkthrough: Rules in Conflict
This example demonstrates the rules, the common "lost context" problem, and the solutions.
'use strict';
const user = {
name: "Alice",
// Rule 3: Implicit Binding
greet: function() {
console.log(`Hello, my name is ${this.name}`);
},
// Demonstrates losing and preserving context
introduce: function() {
console.log(`My name is ${this.name}.`);
function innerFunction() {
// This is a plain function call, so it's Rule 4: Default Binding.
// `this` is `undefined` in strict mode.
// The optional chaining `?.` prevents a TypeError.
console.log(`Inside innerFunction, my name is ${this?.name}`);
}
innerFunction();
const innerArrow = () => {
// Arrow function inherits `this` from the `introduce` scope.
// In the call to `user.introduce()`, `this` is `user`.
console.log(`Inside innerArrow, my name is ${this.name}`);
};
innerArrow();
}
};
// Implicit Binding: `this` is `user` because of the `user.` call-site.
user.greet();
//> Hello, my name is Alice
// `introduce` is called on `user`, so `this` is `user` inside `introduce`.
// But the nested `innerFunction` loses that context.
user.introduce();
//> My name is Alice.
//> Inside innerFunction, my name is undefined
//> Inside innerArrow, my name is Alice
// Rule 2: Explicit Binding
const otherUser = { name: "Bob" };
user.greet.call(otherUser);
//> Hello, my name is Bob
// Rule 1: `new` Binding
function Person(name) {
// When called with `new`, `this` is the new object being created.
this.name = name;
}
const person = new Person("Charlie");
console.log(`New binding: ${person.name}`);
//> New binding: Charlie
Visualizing the Precedence
This flowchart shows the order of operations for determining this.
Try it
Refactor the user.introduce method from the code example. Remove the innerFunction and innerArrow helpers. Instead, use setTimeout to log the user's name after 100ms. First, pass user.greet directly as the callback to see it fail. Then, fix it once using .bind(user) and a second time using an arrow function wrapper.
Next: Asynchronous JavaScript: Callbacks & Promises, where controlling this is critical.
Lock it in — apply this lesson under interview conditions.