The Four Binding Rules
What this refers to is decided when a function is called, not when it is written, and there are exactly four rules that decide it.
this is not fixed at definition time. Four rules settle it at every call, in a strict precedence order: new, then explicit binding with call/apply/bind, then the object before the dot, then the default. Knowing the order makes every case predictable.
EXERCISE
1this Is Decided at Call Time
The single fact that makes everything else in this unit follow: a function does not carry a this with it.
Most confusion about this comes from one wrong assumption: that a function's this is fixed when you write the function. It is not. The same function body can produce four different values of this depending only on how you call it.
Here is that claim demonstrated with one function and no changes to it.
One function, four calls, four answers:
function whoAmI() {
return this;
}
const obj = { name: "Ada", whoAmI };
console.log(obj.whoAmI() === obj); // true
console.log(whoAmI() === undefined); // true (in strict mode / a module)
console.log(whoAmI.call({ id: 7 })); // { id: 7 }
console.log(new whoAmI()); // whoAmI {}
The function never changed. Its text is three lines and it was defined once. Everything that varied happened at the call site.
This is genuinely unusual. In most languages a method belongs to a class and this is settled by where the method lives. decided differently: a function is a standalone value that can be attached to any object, passed anywhere, and called in several ways, so this has to be worked out fresh each time.
Which is why moving a function breaks it:
const user = {
name: "Ada",
greet() {
return `Hi, ${this.name}`;
},
};
console.log(user.greet()); // Hi, Ada
const greet = user.greet; // the same function, pulled out
console.log(greet()); // TypeError: Cannot read properties of undefined
Nothing was copied or modified. greet and user.greet are the identical function object. The first call has user to the left of the dot; the second has nothing, so this is undefined and reading .name from it throws.
That small example is the root of a very large share of real bugs, and lesson 4 is devoted to it.
So the question to ask is always about the call, never the definition:
// Wrong question: "what is this inside greet?"
// Right question: "what is this for THIS CALL of greet?"
user.greet(); // called with user before the dot
greet(); // called with nothing before it
greet.call(user); // called with user supplied explicitly
Pro Tip: When you are debugging a
thisproblem, do not read the function. Read the call site. Find the exact line where the function is invoked and look at what is immediately to the left of the parentheses. That is where the answer lives, every time, and it is the habit that turns this topic from guesswork into a lookup.
EXERCISE
2The Four Rules, in Order
Four rules can apply to any call, and when more than one could, the highest priority wins.
Every call resolves this by checking four rules. They are not alternatives you pick between; they are a priority list checked from the top.
Rule 1, highest priority: was new used?
function Person(name) {
this.name = name;
}
const ada = new Person("Ada");
console.log(ada.name); // Ada
If new is present, this is the brand new object being constructed, and nothing else can override that. This is step 3 of the four steps from Unit 1.
Rule 2: was this supplied explicitly, with call, apply or bind?
function greet() {
return `Hi, ${this.name}`;
}
console.log(greet.call({ name: "Ada" })); // Hi, Ada
console.log(greet.apply({ name: "Bob" })); // Hi, Bob
You are naming the object directly. The next two lessons cover these three methods properly.
Rule 3: is there an object immediately before the dot?
const user = {
name: "Ada",
greet() {
return `Hi, ${this.name}`;
},
};
console.log(user.greet()); // Hi, Ada -> this is user
Only the last object before the dot counts, which surprises people:
const outer = {
name: "outer",
inner: {
name: "inner",
greet() {
return this.name;
},
},
};
console.log(outer.inner.greet()); // "inner", not "outer"
Reading a chain of dots left to right, everything before the final dot is only navigation. It tells JavaScript where to find the function; it does not participate in the call. Only the object the function was reached through, at the last step, becomes this.
Rule 4, lowest priority: none of the above.
function greet() {
return this;
}
console.log(greet()); // undefined in strict mode and in every ES module
// the global object in old non-strict scripts
This is the rule that changed between old and modern JavaScript, and it changed for a good reason. In the original language an unbound this became the global object, so a mistyped call quietly wrote globals instead of failing. Strict mode made it undefined so the mistake throws at the point it happens, and since every ES module is strict, this is now what you will see in any file you write.
And the precedence, demonstrated:
function show() {
return this.label;
}
const a = { label: "implicit", show };
const bound = a.show.bind({ label: "explicit" });
console.log(a.show()); // implicit rule 3
console.log(bound()); // explicit rule 2 beats rule 3
console.log(new bound()); // undefined rule 1 beats rule 2
Check the rules top down and stop at the first match: new, then an explicit call/apply/bind, then the object before the dot, then the default. Four checks, in that order, answers every case. When two rules seem to both apply, the higher one has already won and the lower one never ran.
EXERCISE
3Arrow Functions Do Not Play This Game
An arrow function has no this of its own, which means none of the four rules apply to it at all.
Everything above describes ordinary functions. Arrow functions work on a completely different principle, and treating them as shorter ordinary functions is where people get hurt.
An arrow function does not have a this. Not a default one, not an undefined one: the slot does not exist. So when you write this inside an arrow, JavaScript does what it does for any other variable it cannot find locally. It looks outward to the enclosing scope, exactly as it would for a variable you had closed over.
Which means the four rules simply do not apply:
const obj = {
name: "Ada",
regular() {
return this.name;
},
arrow: () => this?.name,
};
console.log(obj.regular()); // Ada rule 3 applied
console.log(obj.arrow()); // undefined no rule applied
The object before the dot made no difference. An object literal is not a scope, so the arrow looked past it to whatever this meant in the surrounding code, which at the top level of a module is undefined.
Explicit binding cannot override it either:
const arrow = () => this;
console.log(arrow.call({ name: "Ada" })); // NOT { name: 'Ada' }
call sets a function's this, and an arrow has no slot to set. The argument is accepted and quietly ignored.
But the same property is exactly why arrows are useful inside methods:
const timer = {
name: "countdown",
startBroken() {
setTimeout(function () {
console.log(this.name); // undefined: a plain call, rule 4
}, 100);
},
startFixed() {
setTimeout(() => {
console.log(this.name); // countdown: inherited from startFixed
}, 100);
},
};
In startFixed, this inside the method is timer by rule 3. The arrow has no this of its own, so it uses the method's. The callback keeps working no matter how setTimeout chooses to call it, which is the whole reason arrows took over callbacks.
Pro Tip: Use a normal function when the object calling it should decide
this, which means object methods, constructors and prototype methods. Use an arrow when you wantthisto stay whatever it already was, which means callbacks written inside a method. Choosing by that question rather than by which looks shorter means you will essentially never be surprised.
