Enforce calling of unbound methods within their expected scope.
Class method functions do not preserve the class scope when passed as standalone variables ("unbound"). As such, this does not refer to the current class. To resolve this issue, you can use this: void or an arrow function.
// code-linter.json5
{
"rules": {
"@typescript-eslint/unbound-method": "error"
}
} class MyClass {
public logUnbound(): void {
this.logUnbound();
}
public logBound = () => {
this.logUnbound();
};
}
const instance = new MyClass();
// logBound will always be bound with the correct scope
const logBound = instance.logBound;
logBound(); class MyClass {
public logUnbound(): void {
this.logUnbound();
}
public logBound = () => {
this.logUnbound();
};
}
const instance = new MyClass();
// logBound will always be bound with the correct scope
const logUnbound = instance.logUnbound;
logUnbound(); plugin:@typescript-eslint/all
For details about how to configure Code Linter check rules, see Code Linter.