How the this Keyword Works in JavaScript in Every Context
The value of this is set by how a function is called, in four rules and one exception for arrow functions. See each rule, the lost this bug and how to fix it.

Cannot read properties of undefined (reading 'name') is the error message a lost this produces, and almost everyone meets it the first time they pass a method as a callback. The keyword is hard because its value is not fixed by where the function is written, the way variable scope is. It is set when the function is called, by a short list of rules, and once the list is memorized, you can read any call and say what this will be. This post puts the rules in order of priority, shows each with real output from Node.js 24 as an ES module, and covers the arrow function exception and the fixes for the lost receiver. The scope side of the story is in the post on lexical scope, and the mode difference that makes the default undefined is in the post on strict mode.
The four rules, in priority order
For a regular function, check these in order and stop at the first that applies.
| Priority | Call form | this is |
|---|---|---|
| 1 | new Fn() | The new object being constructed |
| 2 | fn.call(obj), fn.apply(obj), a function from fn.bind(obj) | obj |
| 3 | obj.fn() | obj, the thing left of the dot |
| 4 | fn() | undefined in strict mode, the global object in sloppy mode |
Arrow functions skip the table and use the this of the code around them.
Rule 3 and the lost receiver
A method call sets this to the object before the dot. Copying the method into a variable removes the object.
const user = {
name: "Ada",
greet() {
return "hello " + this.name;
},
};
console.log(user.greet());
const detached = user.greet;
try {
console.log(detached());
} catch (error) {
console.log(error.name + ": " + error.message);
}
const wrapper = { run: user.greet, name: "Grace" };
console.log(wrapper.run());hello Ada
TypeError: Cannot read properties of undefined (reading 'name')
hello GraceThe first call has user before the dot, so this is user. The detached call has nothing before the call parentheses, so rule 4 gives undefined, and reading .name throws. The last line shows that the function itself has no owner: assigned to a different object, the same function uses that object. It is the call expression that decides.
The detached case is exactly what happens when a method is passed as a callback.
class Logger {
prefix = "[app]";
log(message) {
return this.prefix + " " + message;
}
}
const logger = new Logger();
console.log(["a", "b"].map((m) => logger.log(m)));
try {
console.log(["a", "b"].map(logger.log));
} catch (error) {
console.log(error.name + ": " + error.message);
}[ '[app] a', '[app] b' ]
TypeError: Cannot read properties of undefined (reading 'prefix')Calling through logger.log(m) inside an arrow keeps the receiver. Passing logger.log itself hands map a bare function, which calls it with no object. This is the bug behind many React class component handlers, addEventListener callbacks and promise chains.
Rule 2: call, apply and bind
call and apply invoke a function immediately with a chosen this, and differ only in how they pass arguments. bind returns a new function whose this is fixed.
function describe(greeting, punctuation) {
return greeting + ", " + this.name + punctuation;
}
const ada = { name: "Ada" };
const grace = { name: "Grace" };
console.log(describe.call(ada, "Hello", "!"));
console.log(describe.apply(grace, ["Hi", "?"]));
const sayToAda = describe.bind(ada, "Welcome");
console.log(sayToAda("."));
console.log(sayToAda.call(grace, ";"));Hello, Ada!
Hi, Grace?
Welcome, Ada.
Welcome, Ada;call takes arguments one at a time and apply takes them as an array. bind can also fix leading arguments, as "Welcome" here. The last line is the important one: a bound function ignores a later call, because the binding is permanent, so this stays ada even when another object is passed.
Rule 1: new
Calling a function with new creates a fresh object, runs the function with this set to it and returns it.
function Point(x, y) {
this.x = x;
this.y = y;
}
const p = new Point(1, 2);
console.log(p);
const Bound = Point.bind({ x: 99 });
const q = new Bound(3, 4);
console.log(q.x, q.y);
console.log(q instanceof Point);
class Box {
constructor(label) {
this.label = label;
}
}
console.log(new Box("crate"));Point { x: 1, y: 2 }
3 4
true
Box { label: 'crate' }The constructor filled the new object. The bound version is the case that proves the priority order: new beats bind, so the bound this of { x: 99 } was ignored, and a new Point was created anyway. A class constructor works the same way, and calling a class without new throws, which a plain function constructor does not do.
Arrow functions
An arrow function has no this. When its body mentions this, the lookup goes outward through the enclosing scopes, exactly like an ordinary variable, and uses the first function that has one. That makes arrows the right tool for callbacks that should keep the surrounding method's this.
const timer = {
label: "tick",
start() {
const regular = [1, 2].map(function (n) {
return this === undefined ? "lost " + n : this.label;
});
const arrow = [1, 2].map((n) => this.label + " " + n);
return { regular, arrow };
},
};
console.log(timer.start());
const arrowFn = () => this;
console.log(arrowFn());
console.log(arrowFn.call({ label: "ignored" }));{ regular: [ 'lost 1', 'lost 2' ], arrow: [ 'tick 1', 'tick 2' ] }
undefined
undefinedThe regular callback was called plainly, so this was undefined inside it, while the arrow callback used timer from the start method. At the top level of an ES module, this is undefined, so an arrow function defined there returns undefined, and call cannot change it. Arrows are not a replacement for every function, though. They cannot be constructors, they have no arguments object, and they make poor object methods when the method needs its receiver.
const counter = {
count: 0,
incrementArrow: () => {
return typeof this;
},
incrementMethod() {
this.count += 1;
return this.count;
},
};
console.log(counter.incrementArrow());
console.log(counter.incrementMethod());undefined
1The arrow property uses the module-level this, which is undefined, so it never sees counter. Use method syntax for object methods, and arrows inside them.
Fixing a lost this
Four fixes cover nearly every case, and the right one depends on what you control.
class Button {
label = "Save";
handleBound = this.handle.bind(this);
handleField = () => this.label;
handle() {
return this.label;
}
}
const button = new Button();
const { handle, handleBound, handleField } = button;
try {
handle();
} catch (error) {
console.log("plain: " + error.name);
}
console.log("bound:", handleBound());
console.log("field:", handleField());
console.log("wrapper:", [1].map(() => button.handle())[0]);plain: TypeError
bound: Save
field: Save
wrapper: SaveThe plain method fails when detached. Binding it once in a field, using an arrow function field and wrapping the call in an arrow all work. An arrow field creates one function per instance, which costs memory on a class with thousands of instances and a prototype method does not. For event handlers on a few components that cost is irrelevant, and for a data class with many instances, bind at the call site.
Why classes make the problem visible
Methods defined in a class body live on the prototype, and they are shared by every instance. That is why they have no fixed receiver: the same function object serves every instance, so the language cannot bake one in. The post on classes being functions shows the prototype link that explains it. Class bodies are always strict, so a detached method sees undefined, and the failure is immediate. In a sloppy constructor function the same detached call would read a property from the global object, and return undefined quietly, which is the version of this bug that survives to production.
When you review code with callbacks, apply a one-line test to every function reference that is not followed by parentheses: is this a method of an object that uses this? If so, it needs a wrapper, a bind or an arrow field.
this in other places
A handful of other contexts have a defined this.
| Place | this |
|---|---|
| Top level of an ES module | undefined |
| Top level of a CommonJS file | module.exports |
| Inside a class static method | The class |
| A getter or setter | The object the property was read from |
| A DOM event handler as a regular function | The element the listener is attached to |
setTimeout(function () {}) in a browser | window, or undefined in strict mode |
The DOM row is the reason addEventListener("click", function () { this.classList.add("on"); }) works, and also the reason switching it to an arrow function breaks, since the arrow no longer sees the element. Use event.currentTarget when you want the code to survive that change.
Typing this in TypeScript
TypeScript can check this. With the strict option, noImplicitThis flags code where this would have the implicit type any, and a function can declare the type it expects as a fake first parameter.
interface User {
name: string;
}
function greet(this: User, greeting: string): string {
return greeting + " " + this.name;
}
const ada: User = { name: "Ada" };
greet.call(ada, "Hello");
// Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'User'.
greet("Hello");The annotation is erased at compile time and exists only for the checker, which now rejects the plain call that would have lost the receiver.
Where this advice stops
If your code is mostly functions and plain objects, you will rarely need this at all, and an approach that passes the object as an argument avoids the whole topic. Classes and DOM handlers are where it matters most, and framework code that wraps them usually hides it.
Do not use bind in a hot path that runs every render, since each call makes a new function. And do not rely on sloppy-mode this, which falls back to the global object, in code you intend to keep.
The semantics are defined in the specification under the this keyword, and MDN's this reference lists every context.


