Navigate
Search topics, hooks, and fundamentals
JavaScript has four rules that determine what this becomes. They have a strict priority order — knowing it means you can always predict this.
Each rule has a priority. When multiple rules could apply, the higher-priority rule wins. Explore each one:
The most common rule — when a function is called as a method, the object before the dot becomes this:
const hero = {
name: "Wolf",
announce() {
console.log(this.name + " is here!");
},
};
hero.announce(); // "Wolf is here!"
// this = hero (the object before the dot)call, apply, and bind let you manually choose this. bind locks it permanently:
function shapeshift(newForm) {
console.log(this.name + " becomes " + newForm);
}
const wolf = { name: "Wolf" };
const eagle = { name: "Eagle" };
shapeshift.call(wolf, "dragon"); // "Wolf becomes dragon"
shapeshift.apply(eagle, ["phoenix"]); // "Eagle becomes phoenix"
const wolfShift = shapeshift.bind(wolf);
wolfShift("serpent"); // "Wolf becomes serpent" (always wolf)The new keyword creates a fresh object and forces this to point to it. Highest priority:
function Shapeshifter(name) {
// new creates a fresh object and sets this to it
this.name = name;
this.form = "base";
}
const hero = new Shapeshifter("Mystique");
console.log(hero.name); // "Mystique"
console.log(hero.form); // "base"When rules conflict, the higher-priority one wins: new > explicit > implicit > default.
const obj = {
name: "implicit",
greet() { return this.name; },
};
// explicit beats implicit
obj.greet.call({ name: "explicit" }); // "explicit"
// new beats explicit
const Bound = obj.greet.bind({ name: "bound" });
const instance = new Bound();
console.log(instance.name); // undefined — new won!this = that objectcall/apply/bind set this manuallythis = object before the dotthis = window/undefined