Sub topic 1
How JavaScript Decides What this Is
Most variables in JavaScript get their value from where the code is written. You can read a closure, look at the surrounding braces, and tell what each name refers to. this does not work that way. Its value is set fresh each time a function runs, and it depends on how that particular call was made. The same function can see a different this on every call.
This chapter builds the mental model the rest of the tutorial uses: find the call site, read the shape of the call expression, and apply a short list of rules. Later chapters cover each rule in detail. Here the goal is to learn where to look and what question to ask.
Prerequisites
This chapter assumes you are comfortable with the following:
- JavaScript functions and function expressions, including passing functions as values
- Objects, properties, and methods (functions stored as object properties)
- Basic scope and closures: how an inner function reads variables from an outer one
- ES2015+ syntax such as arrow functions, shorthand methods, and classes
All examples run in Node.js or a browser console. Most start with 'use strict'; so the results don't depend on the environment. Strict mode changes one of the rules, and a later chapter explains how.
The Core Idea: Call Site, Not Definition Site
Here is one function attached to two objects and also called on its own:
'use strict';
function describe() {
return this ? this.name : 'no this';
}
const ada = { name: 'Ada', describe };
const alan = { name: 'Alan', describe };
console.log(ada.describe()); // 'Ada'
console.log(alan.describe()); // 'Alan'
console.log(describe()); // 'no this'
console.log(describe.call({ name: 'Grace' })); // 'Grace'There is only one describe function. ada.describe and alan.describe hold the same function object, and ada.describe === alan.describe is true. Still, the four calls produce four different results. The only difference between them is how each call is written.
So this is an implicit parameter. Every regular function call passes it, and the caller picks its value through the syntax of the call. It is not part of the function, not fixed when the function is created, and not looked up through scope.
What a Call Site Is
A call site is the place in the code where a function is invoked: the expression ending in (...) that runs it. That is different from where the function is declared, and different from the function that happens to be running at the time.
'use strict';
const logger = {
prefix: '[app]',
log(message) {
return `${this.prefix} ${message}`;
}
};
function handleRequest() {
// The call site of log is this line, inside handleRequest.
return logger.log('request received');
}
console.log(handleRequest()); // '[app] request received'Three functions are involved: the top-level code, handleRequest, and log. To work out this inside log, ignore the other two and look at the expression that called log: logger.log('request received'). That call site has an object before the dot, so this is logger.
handleRequest itself was called as a plain handleRequest(), so its own this is undefined in strict mode. That has no effect on log. Every call gets its own this, and nothing is inherited down the call stack.
When debugging, browser devtools and Node's inspector show the call stack. The frame just below the current function is the caller, and the line it points to is the call site you need to read.
The Rules at a Glance
Once you have found the call site, you ask a few questions in order. Each question matches one binding rule, and each rule gets a full chapter later. This table is a map, not the full explanation.
| How the function is called | Example | this inside the function | Rule name |
|---|---|---|---|
| With `new` | `new Box(1)` | A newly created object | new binding |
| Through `call`, `apply`, or a function made by `bind` | `fn.call(obj)` | The object passed in | explicit / hard binding |
| As a property of an object | `obj.method()` | The object before the dot | implicit binding |
| As a plain function | `fn()` | `undefined` in strict mode, `globalThis` in sloppy mode | default binding |
| Arrow function, called any way | `arrow()` | The `this` of the enclosing scope | lexical this |
The order of the rows matters. If more than one rule seems to apply, the one higher in the table wins. Most real calls match only one row, so you rarely need to think about precedence, but the cases where it matters are covered in the chapter on binding precedence.
Reading the Shape of a Call Expression
The implicit-binding question, "is there an object before the dot?", has some edge cases. They make more sense once you know what the engine actually checks.
When JavaScript evaluates obj.method, the specification produces a Reference: a pair holding the base object (obj) and the property name ('method'). If that Reference is called directly, the engine passes the base object as this. If the Reference is first turned into a plain value, for example by assigning it to a variable, the base object is lost and the call has no this to pass.
That one detail explains all of these results:
'use strict';
const obj = {
name: 'obj',
whoAmI() {
return this === undefined ? 'undefined' : this.name;
}
};
console.log(obj.whoAmI()); // 'obj' dot access, Reference called directly
console.log(obj['whoAmI']()); // 'obj' bracket access is also a Reference
console.log(obj?.whoAmI()); // 'obj' optional chaining keeps the base
console.log((obj.whoAmI)()); // 'obj' grouping parentheses keep the Reference
const f = obj.whoAmI;
console.log(f()); // 'undefined' the variable holds only the function value
console.log((0, obj.whoAmI)()); // 'undefined' the comma operator produces a plain value
console.log((obj.whoAmI || null)()); // 'undefined' so does ||Plain grouping parentheses don't change anything, because (obj.whoAmI) is still a Reference. Operators such as ,, ||, ??, and = evaluate their operands to values, and a value has no base object. Bundlers and transpilers sometimes emit (0, obj.fn)() for exactly this reason: it calls fn without passing obj as this.
A practical rule: look at what comes right before the ( of the call. If it is a property access (a.b, a[b], a?.b), the object on the left becomes this. If it is anything else, such as a bare name, the result of another call, or the result of an operator, there is no implicit this.
Only the last property access counts. In app.services.logger.log(), this is app.services.logger, not app.
What this Is Not
Many bugs with this come from expecting it to behave like something else. Three wrong ideas come up often.
It is not the function itself
The name sounds like it should mean "this function." It doesn't. To store state on a function, refer to the function by name.
'use strict';
function tally() {
// this.count++ would throw: this is undefined for a plain call
tally.count = (tally.count || 0) + 1;
return tally.count;
}
tally();
console.log(tally()); // 2It is not inherited by nested functions
An inner regular function is a separate function with its own call site. Being written inside a method gives it no access to the method's this.
'use strict';
const report = {
title: 'Q3 summary',
print() {
function heading() {
return this; // heading() is a plain call below
}
return heading();
}
};
console.log(report.print()); // undefinedprint was called as report.print(), so its this is report. heading was called as heading(), so its this follows the default rule. Closures capture variables, and this is not a variable. Before arrow functions existed, people wrote const self = this; in the method and used self inside the inner function. That works because self is an ordinary variable that the closure can capture.
It is not the object that "owns" the function
Writing a method inside an object literal does not tie the function to that object. The literal only stores a reference to the function in a property, and any other object or variable can hold the same reference. What decides this is which object the call goes through.
'use strict';
const cat = {
sound: 'meow',
speak() {
return this.sound;
}
};
const dog = { sound: 'woof', speak: cat.speak };
console.log(cat.speak()); // 'meow'
console.log(dog.speak()); // 'woof', same function, different call siteCommon Errors
| Symptom | Likely cause | Where it is covered |
|---|---|---|
| `TypeError: Cannot read properties of undefined` inside a method | The method was called without an object before the dot, often after being passed as a callback | Why Methods Lose Their this |
| A property is quietly `undefined`, or a stray global variable appears | Sloppy-mode default binding pointed `this` at `globalThis` | Plain Function Calls: Sloppy vs Strict Mode |
| `this` is wrong inside a `setTimeout` or `forEach` callback | The callback is a regular function called plainly by the runtime | Callbacks, thisArg, and Event Handlers |
| `call` or `bind` seems to have no effect | The function is an arrow function or already bound | Locking this with bind; Arrow Functions and Lexical this |
To diagnose any of these, go back to the core question: find the exact expression that invokes the function, and check which rule it matches. If the call happens inside library or runtime code (a timer, an array method, an event system), you can't see the call site, so you need to know that API's convention or make this independent of the call site.
Exercise
In strict mode, what does each line log, and why? const shop = { name: 'Corner Shop', getName() { return this === undefined ? 'undefined' : this.name; } }; const other = { name: 'Other', getName: shop.getName }; const g = shop.getName; console.log(other.getName()); console.log(g()); console.log((shop.getName)()); console.log((shop.getName ?? null)());
Show answer
'Corner Shop' is never logged as a trick: the lines log 'Other', 'undefined', 'Corner Shop', and 'undefined'. other.getName() goes through other, so this is other. g() is a plain call on a variable, so this is undefined in strict mode. (shop.getName)() uses grouping parentheses, which keep the property reference, so this is shop. The ?? operator turns the reference into a plain function value, so that call has no base object and this is undefined.
Exercise
A teammate writes the code below and expects 'Total: 30'. In strict mode it throws instead. Find the call site that causes the error and explain it using the rules from this chapter. const cart = { items: [10, 20], total() { function sum() { return this.items.reduce((a, b) => a + b, 0); } return 'Total: ' + sum(); } }; console.log(cart.total());
Show answer
The problem is the call site sum(). cart.total() correctly sets this to cart inside total, but sum is a separate regular function invoked as a plain call, so its this follows default binding and is undefined in strict mode. Reading this.items then throws a TypeError. Nested functions do not inherit this. Fixes include const items = this.items; captured by closure, sum.call(this), or making sum an arrow function, which uses total's this.
Exercise
Why is it accurate to describe this as an implicit parameter rather than a variable in scope?
Show answer
Like a parameter, its value is supplied fresh by each call and can differ every time the same function runs. The caller chooses it through the form of the call: the object before the dot, call/apply/bind, or new. A scoped variable is resolved through the surrounding code and captured by closures. this is not captured that way by regular functions, which is why a nested regular function does not see its outer method's this.