The this trap and arrow methods
In JavaScript this depends on how a function is called, so a method passed as a callback loses its object. In strict mode this becomes undefined, as in retry(login.open). The fixes are a wrapper () => login.open(), bind or an arrow property, which is created per instance and does not work with super. The compiler does not catch this, so enable the ESLint rule unbound-method.
TypeScript · Classes
retry(login.open) fails with "Cannot read properties of undefined" while login.open() works. What changed?
A retry helper accepts a function, and the author passes it a Page Object method: retry(login.open). The method looks perfectly normal in the class, TypeScript underlines nothing, and at run time a TypeError appears inside the method. The same method called as login.open() works. This lesson is about why this in JavaScript depends on the call, and how to fix it without surprises.
How it works and why. In JavaScript the value of this inside an ordinary function is determined not by where it was declared but by how it was called. When you write login.open(), the object before the dot becomes this. When the function is put into a variable or passed as an argument, the link to login is lost: the call fn() goes without an object. Class methods live on the prototype and are not bound to an instance, and a class body runs in strict mode, so this becomes undefined instead of the global object, and this.page fails.
async function retry<T>(fn: () => Promise<T>, times = 3): Promise<T> {
for (let i = 1; ; i++) {
try {
return await fn();
} catch (e) {
if (i >= times) throw e;
}
}
}
class LoginPage {
constructor(private readonly page: Page) {}
async open() {
await this.page.goto('/login');
}
}
const login = new LoginPage(page);
await retry(login.open);
// TypeError: Cannot read properties of undefined (reading 'page')
await retry(() => login.open()); // works
Where this comes from
Why the compiler is silent. The type of login.open is just () => Promise<void>: for ordinary class methods TypeScript does not track that a function waits for a particular this, and accepts it wherever the signature fits. A method can be detached accidentally too, for example in array.map(helper.format).
Example: three ways to fix it.
class LoginPage {
constructor(private readonly page: Page) {}
async open() {
await this.page.goto('/login');
}
openArrow = async () => {
await this.page.goto('/login');
};
}
await retry(() => login.open()); // wrapper
await retry(login.open.bind(login)); // bind
await retry(login.openArrow); // arrow property
The wrapper () => login.open() is simplest: the call goes through a dot again, and this is right. bind creates a new function with a fixed this; in TypeScript under strictBindCallApply it keeps the types. An arrow property openArrow = async () => … captures the instance this when the object is created, so it can be passed anywhere.
An arrow property has a cost. It is created separately for each instance and does not live on the prototype, so it takes memory per instance. A subclass cannot call it through super.openArrow() because the prototype has no such function. It cannot be mocked or replaced through the prototype. For a Page Object, with few instances, this is usually acceptable, and such a method is rarely passed as a callback.
A method or an arrow property
Wrapper or bind
One function on the prototype, works with super and mocking. When passing it, this must be bound.
Captures this
Can be passed as is. A separate function in each instance, super does not work.
How to prevent it. TypeScript can require an explicit this: a this: Foo parameter in a function signature forbids a call without the right context. For ordinary methods a more useful tool is the ESLint rule from typescript-eslint that catches passing an unbound method:
{
"rules": {
"@typescript-eslint/unbound-method": "error"
}
}
The rule unbound-method needs a type-checked configuration and flags a reference to a class method without a call. Arrow properties and bound functions are not touched by it.
Limits and alternatives.
- An arrow function has no
thisof its own: it takes it from the surrounding scope. So inside a class method() => this.xis safe. - The problem is not only about classes: a method of a plain object
{ read() { return this.v } }behaves the same way. - An alternative: do not rely on
thisat all and write a Page Object as a set of functions with a closure. - Before passing a library method (not your own class's) as a callback, check the documentation: what it expects from
thisis not guaranteed.
Common mistakes.
- Passing
obj.methodas a callback (toretry,map,setTimeout):thisis lost. - Making all methods arrow properties "just in case": they lose
superand the prototype. - Relying on the compiler to catch it: without an ESLint rule it does not.
- Confusing
bindwith a call:fn.bind(obj)only returns a new function, and only the next call runs it.
Check yourself
Why does retry(login.open) fail while retry(() => login.open()) works, though the method is the same?
Answer
In the first case retry calls the function without an object before the dot, so this is undefined (a class body is strict). In the second the call goes as login.open() and this is login.
What is the cost of an arrow property open = async () => … instead of an ordinary method?
Answer
The function is created separately for each instance and is not on the prototype, so a subclass cannot call it through super.open() and it cannot be replaced through the prototype. In return this is always right.
this in JavaScript depends on how a function is called, so a method passed as a callback loses its context. I pass an arrow wrapper or use bind. Middle/Senior: The compiler does not catch this, so I turn on the ESLint rule unbound-method and watch for it in review. I use an arrow property selectively: it guarantees this, but it is created per instance and does not work with super.