Navigate
Search topics, hooks, and fundamentals
this is a shape shifter — it becomes whatever called it. In global scope it's the window, in a method it's the object, and when detached it loses its identity entirely.
Unlike most variables, this isn't determined by where a function is written — it's determined by how the function is called. The caller decides the shape.
this changes identityClick a context to see what this becomes. The shape shifter takes on a different identity depending on who summons it:
When a function is called without any owner (a "loose call"), this defaults to the global object — window in browsers:
// In a browser (non-strict mode)
console.log(this); // window
function showThis() {
console.log(this);
}
showThis(); // window (loose call — no owner)In strict mode, loose calls give undefined instead — a much safer default:
"use strict";
function showThis() {
console.log(this);
}
showThis(); // undefined — strict mode doesn't default to windowWhen a function is called as a method (with an object before the dot), this becomes that object:
const shapeshifter = {
form: "wolf",
reveal() {
console.log("I am a " + this.form);
},
};
shapeshifter.reveal(); // "I am a wolf"
// this = shapeshifter (the object before the dot)Copying a method to a variable strips the object context. The function is the same, but the caller is gone:
const shapeshifter = {
form: "wolf",
reveal() {
console.log("I am a " + this.form);
},
};
const detached = shapeshifter.reveal;
detached(); // "I am a undefined" — identity lost!
// The function was copied without its contextExplore different calling scenarios and see what this resolves to in each:
this will bethis is determined at call time, not definition timewindow (or undefined in strict mode)