Sub topic 5
Why Methods Lose Their this
This chapter assumes you know how plain function calls get their this (default binding, sloppy vs strict mode) and how method calls get theirs (implicit binding through the object before the dot). It also assumes you are comfortable with functions as values, closures, and destructuring. The question here is what happens when those two rules meet. You start with a method call, but by the time the function runs, the call has turned into a plain function call.
That is the most common this bug in JavaScript. It is called a lost binding. The function has not changed, and neither has the object. What changed is the way the function is called.
The Core Mistake: Thinking this Belongs to the Function
A method in JavaScript is just a function stored in a property. The function does not remember which object it came from. When you write counter.increment(), the object counter becomes this because of the shape of that call expression. The function definition has nothing to do with it.
'use strict';
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
console.log(counter.increment()); // 1, this is counter
const inc = counter.increment;
try {
inc();
} catch (err) {
console.log(err.constructor.name, err.message);
// TypeError Cannot read properties of undefined (reading 'count')
}inc and counter.increment point to the same function object. You can check with inc === counter.increment, which is true. Only the call site differs. inc() has nothing before a dot, so default binding applies. In strict mode, that makes this equal to undefined, and this.count throws.
What Happens Internally: References and GetValue
The language specification explains this precisely, and the model helps you predict odd cases.
When the engine evaluates a property access such as counter.increment, the result is not yet a plain value. It is a Reference Record. Think of it as a pair: a base value (counter) and a property name ('increment'). A call expression checks what its callee evaluated to:
- If the callee is a property reference, the engine reads the function from it and uses the base value as
this. - If the callee is anything else (a variable, the result of an operator, a value returned from another function), there is no base value.
thisisundefined, and in sloppy modeundefinedis then replaced withglobalThis.
Most operations collapse a reference into a plain value right away. The spec calls this step GetValue. Assignment does it, passing an argument does it, and so do the comma, ||, ??, and ternary operators. After GetValue, the base object is gone.
The Many Ways to Extract a Method
Once you have the reference model, the losing patterns all look alike. Each one turns obj.method into a plain value before the call happens.
Assigning to a variable or another property
The first example showed assignment to a variable. Assigning the method to a property of a different object is not a loss in the same sense. Implicit binding applies again, but to the new object.
'use strict';
const alice = {
name: 'Alice',
hello() {
return `Hi, I am ${this.name}`;
}
};
const bob = { name: 'Bob', hello: alice.hello };
console.log(alice.hello()); // 'Hi, I am Alice'
console.log(bob.hello()); // 'Hi, I am Bob', the object before the dot winsThis works as designed, and it is how prototype methods are shared by many objects. It also confirms that this is never attached to the function.
Destructuring
Destructuring is assignment written differently, so it loses this too.
'use strict';
const account = {
balance: 100,
getBalance() {
return this.balance;
}
};
const { getBalance } = account;
try {
getBalance();
} catch (err) {
console.log(err.message); // Cannot read properties of undefined (reading 'balance')
}This often shows up in code that destructures methods from a module-like object or from a class instance, for example const { save } = repository;.
Passing a method as a callback
Passing a function as an argument copies the value into a parameter. The function you pass in will later call that parameter as a plain function, and you do not control how.
'use strict';
const tally = {
total: 0,
add(n) {
this.total += n;
}
};
try {
[1, 2, 3].forEach(tally.add);
} catch (err) {
console.log(err.message); // Cannot read properties of undefined (reading 'total')
}
Promise.resolve(5)
.then(tally.add)
.catch((err) => console.log('promise:', err.message));
// promise: Cannot read properties of undefined (reading 'total')forEach calls its callback with this set to undefined unless you pass a thisArg. Promise handlers are always called with undefined. Neither of them knows that tally exists.
Timers are a special case
Timers do not follow the simple rule, so be careful. setTimeout(obj.method, 0) loses obj, but this is not always undefined inside the callback:
- In browsers, timer callbacks are called with
thisset towindow, even when the callback is strict. - In Node.js, timer callbacks are called with
thisset to theTimeoutobject thatsetTimeoutreturned.
'use strict';
const job = {
name: 'cleanup',
run() {
console.log(this === job, typeof this, this && this.name);
}
};
setTimeout(job.run, 0);
// Node.js: false object undefined (this is a Timeout object)
// Browser: false object undefined (this is window)Neither environment gives you job. Because this is still an object here, strict mode does not throw. You get undefined properties instead, so the bug fails silently even in strict code.
Sloppy Mode Turns Errors into Silent Corruption
In strict code, a lost binding usually throws a TypeError close to the cause. In sloppy code, this becomes globalThis, and the method then reads and writes global properties.
// Classic script, no 'use strict'
var logger = {
prefix: '[app]',
log(msg) {
return this.prefix + ' ' + msg;
},
setPrefix(p) {
this.prefix = p;
}
};
var log = logger.log;
console.log(log('started')); // 'undefined started'
var setPrefix = logger.setPrefix;
setPrefix('[oops]');
console.log(globalThis.prefix); // '[oops]', a new global was created
console.log(logger.prefix); // '[app]', the real object never changedNothing throws. The output is wrong, and a global variable has appeared that other code can collide with. Modules and class bodies are always strict, which is one reason modern code shows lost bindings as errors instead of corrupted data.
Forms That Keep the Binding, and Forms That Do Not
Some syntax looks like extraction but keeps the reference. Other syntax looks harmless but drops it. The rule is still the same one: an operator either keeps the reference or applies GetValue to it.
'use strict';
const obj = {
id: 'obj',
who() {
return this === undefined ? 'undefined' : this.id;
}
};
console.log(obj.who()); // 'obj'
console.log(obj['who']()); // 'obj', bracket access is a reference too
console.log((obj.who)()); // 'obj', parentheses keep the reference
console.log(obj.who?.()); // 'obj', optional call keeps it
console.log((0, obj.who)()); // 'undefined', comma operator runs GetValue
console.log((obj.who || null)()); // 'undefined', || runs GetValue
console.log((true ? obj.who : 0)()); // 'undefined', ternary runs GetValue
console.log((obj.who = obj.who)()); // 'undefined', assignment returns a value| Call form | Keeps `this`? | Why | Column | Column |
|---|---|---|---|---|
| `obj.m()` / `obj['m']()` | Yes | Callee is a property reference | ||
| `(obj.m)()` | Yes | Grouping does not evaluate the reference | ||
| `obj.m?.()` / `obj?.m()` | Yes | Optional chaining keeps the base | ||
| `const f = obj.m; f()` | No | Variable holds a plain value | ||
| `const { m } = obj; m()` | No | Destructuring is assignment | ||
| `(0, obj.m)()` | No | Comma operator returns a value | ||
| `(a \ | \ | obj.m)()` | No | Logical operators return a value |
| `arr.forEach(obj.m)` | No | Argument passing copies the value | ||
| `setTimeout(obj.m)` | No | Host picks `this` (window or Timeout) |
Diagnosing a Lost Binding
When this is wrong inside a method, work backward from the error:
- Confirm the symptom. Log
thisat the top of the method. Seeingundefined,globalThis,window, aTimeout, or some unrelated object all point to the same cause. - Find the call site. Look at the stack trace. The frame that called your method shows the actual call expression, and it is often inside library code such as
forEach,then, or an event dispatcher. - Find the extraction point. Search your code for the place where the method was read without being called immediately: an assignment, a destructuring, or an argument like
.then(obj.method). - Decide who should own
this. If the method does not needthis, consider making it a standalone function. If it does, fix the call site.
Previewing the Fixes
Later chapters cover the tools in detail. They all solve the same problem: make sure the final call has the right object.
'use strict';
const tally = {
total: 0,
add(n) {
this.total += n;
}
};
// 1. Wrap it so the call still has an object before the dot
[1, 2].forEach((n) => tally.add(n));
// 2. Use the callback's thisArg parameter when the API offers one
[3].forEach(tally.add, tally);
// 3. Create a bound copy with bind (covered in "Locking this with bind")
[4].forEach(tally.add.bind(tally));
console.log(tally.total); // 10The wrapper is usually the clearest fix. It keeps tally.add(n) as a real method call, and readers can see the object in the code. thisArg only works with APIs that accept it. bind makes a new function, which matters if you later need to remove that exact function, for example as an event listener.
Exercises
Exercise
In strict mode, what does each line log, and why? const o = { v: 1, get() { return this?.v; } }; console.log((o.get)()); console.log((o.get, o.get)()); console.log([o.get][0]());
Show answer
The first line logs 1, because grouping parentheses keep the property reference and o becomes this. The second logs undefined, because the comma operator applies GetValue and the call has no base object, so this is undefined and the optional chain returns undefined. The third logs undefined in a different way: [o.get][0] is a property reference whose base is the array, so this is the array, and arrays have no v property.
Exercise
A sloppy-mode script contains const cart = { items: [], add(x) { this.items.push(x); } }; and later document.querySelectorAll('.product').forEach(cart.add). It throws "Cannot read properties of undefined (reading 'push')". Explain the cause and give a fix that keeps cart as this.
Show answer
forEach calls cart.add as a plain function. Because the script is sloppy, this is globalThis, and globalThis.items is undefined, so calling push on it throws. Fix it with a wrapper, .forEach((el) => cart.add(el)), or pass a thisArg, .forEach(cart.add, cart). Note that NodeList.prototype.forEach also passes the index and the list as extra arguments, which add ignores here.
Exercise
Why does setTimeout(job.run, 0) in strict-mode Node.js code not throw, even though job.run reads this.name and job is lost?
Show answer
Node.js calls timer callbacks with this set to the Timeout object, not undefined. Reading a missing property from an object returns undefined without throwing, so the bug is silent. Browsers behave the same way, except that this is window.