Sub topic 5
Why Methods Lose Their this
This chapter assumes you know how implicit binding works: calling obj.method() sets this to obj. It also assumes you are comfortable with function references, callbacks, and strict mode's default binding, where a plain call leaves this as undefined.
This chapter covers one of the most common this bugs. A method works when you call it directly, then fails once you pass it somewhere else.
A Method Is Just a Function Stored on an Object
JavaScript does not tie a function to the object it was written inside. A method is an ordinary function value stored in a property. The obj. prefix only matters at the moment of the call. The engine sees a property access followed directly by a call, and it uses the object before the dot as this.
When you read the property without calling it, you get the bare function. The object is not attached to it. If that function is called later as a plain function, default binding applies.
'use strict';
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
console.log(counter.increment()); // 1, called through counter
const inc = counter.increment; // copy the function reference
try {
inc(); // plain call: this is undefined
} catch (err) {
console.log(err instanceof TypeError); // true
}inc and counter.increment are the same function. Only the call site changed.
The Common Ways to Lose this
Assigning to a variable or destructuring
Destructuring does the same thing as assigning to a variable: it reads the property and stores the bare function.
'use strict';
const logger = {
prefix: '[app]',
log(msg) {
console.log(`${this.prefix} ${msg}`);
}
};
const { log } = logger;
try {
log('hello');
} catch (err) {
console.log(err.message); // Cannot read properties of undefined (reading 'prefix')
}Passing a method as a callback
This case is easy to miss because the call happens out of your sight. When you pass logger.log as an argument, the receiving function gets only the function value. It then calls that value however it chooses, usually as a plain function.
'use strict';
const logger = {
prefix: '[app]',
log(msg) {
console.log(`${this.prefix} ${msg}`);
}
};
function runTwice(fn) {
fn('first'); // plain call inside runTwice
fn('second');
}
try {
runTwice(logger.log);
} catch (err) {
console.log('lost this:', err instanceof TypeError); // lost this: true
}
try {
['a', 'b'].forEach(logger.log);
} catch (err) {
console.log('lost this again:', err instanceof TypeError); // lost this again: true
}Timers, promise handlers, event systems, and array methods all behave this way. The host decides how to call your function. Unless it documents otherwise, do not expect it to supply your object.
Expressions that drop the reference
Wrapping a member access in parentheses keeps the binding. Any expression that evaluates to the function first drops it.
| Call expression | this inside the method |
|---|---|
| `obj.method()` | `obj` |
| `(obj.method)()` | `obj` (grouping alone does not drop the reference) |
| `obj.method?.()` | `obj` |
| `(0, obj.method)()` | `undefined` in strict mode |
| `(obj.method = obj.method)()` | `undefined` in strict mode |
| `(cond ? obj.method : other)()` | `undefined` in strict mode |
The comma, assignment, and conditional operators produce a plain function value, so the call that follows is a plain call.
Sloppy Mode Hides the Bug
In strict code, including modules and class bodies, a lost this is undefined, so accessing a property on it throws right away. In a sloppy classic script, this falls back to globalThis. Then this.count++ quietly creates or changes a global count and returns NaN, and nothing throws. If a method returns odd values only when used as a callback, suspect a lost binding.
Diagnosing and Fixing
To diagnose a lost binding, find the line where the function is actually invoked. Then ask whether an object sits directly before the dot in that call. If the function was passed or stored first, the answer is usually no.
The simplest fix is to keep the method call intact by wrapping it:
'use strict';
const logger = {
prefix: '[app]',
log(msg) {
console.log(`${this.prefix} ${msg}`);
}
};
['a', 'b'].forEach((msg) => logger.log(msg)); // [app] a, [app] bThe wrapper is what gets passed around, and it calls logger.log(...) as a method every time. Later chapters cover the other fixes: call and apply, bind, arrow functions, and thisArg parameters.
Exercise
In strict mode, given const user = { name: 'Lin', hi() { return this.name; } }, which of these calls return 'Lin': (a) user.hi(), (b) (user.hi)(), (c) const f = user.hi; f(), (d) [1].map(user.hi)?
Show answer
Only (a) and (b) return 'Lin'. Grouping with parentheses keeps the property reference. In (c) the function is called as a plain function and throws a TypeError because this is undefined. In (d), map calls hi without a thisArg, so this is undefined and it also throws.
Exercise
A sloppy-mode script runs setTimeout(counter.increment, 0) in a browser, and counter.count stays 0 with no error. Why, and what one-line change fixes it?
Show answer
setTimeout calls the bare function, so in sloppy mode this is the global object (window). this.count++ changes window.count, which becomes NaN, and counter.count is never touched. Pass a wrapper instead: setTimeout(() => counter.increment(), 0).