Skip to content

Anti-pattern : Prefer that unbound methods are called with their expected scope #269

Description

@philipjonsen

DESCRIPTION

Warning is raised when a method is used outside of a method call.

Class functions don't preserve the class scope when passed as standalone variables.

BAD PRACTICE

class MyClass {
public log(): void {
console.log(this);
}
}

const instance = new MyClass();

// This logs the global scope (window/global), not the class instance
const myLog = instance.log;
myLog();

// This log might later be called with an incorrect scope
const { log } = instance;

RECOMMENDED

class MyClass {
public logUnbound(): void {
console.log(this);
}

public logBound = () => console.log(this);
}

const instance = new MyClass();

// logBound will always be bound with the correct scope
const { logBound } = instance;
logBound();

// .bind and lambdas will also add a correct scope
const dotBindLog = instance.logBound.bind(instance);
const innerLog = () => instance.logBound();

Look here to fix it, and remember to sponsor or give me a star for my work :)

Avoid referencing unbound methods which may cause unintentional scoping of this. If your function does not access this, you can annotate it with this: void, or consider using an arrow function instead
src/providers/ethers.test.ts

import EthersProvider from './ethers';

const { createFixtureLoader, provider } = waffle;
const { isProvider, send } = EthersProvider;

const loadFixture = createFixtureLoader(provider.getWallets(), provider);
Avoid referencing unbound methods which may cause unintentional scoping of this. If your function does not access this, you can annotate it with this: void, or consider using an arrow function instead
src/providers/ethers.test.ts

import EthersProvider from './ethers';

const { createFixtureLoader, provider } = waffle;
const { isProvider, send } = EthersProvider;

const loadFixture = createFixtureLoader(provider.getWallets(), provider);
Avoid referencing unbound methods which may cause unintentional scoping of this. If your function does not access this, you can annotate it with this: void, or consider using an arrow function instead
src/providers/http.test.ts

import HttpProvider from './http';

const { createFixtureLoader, provider } = waffle;
const { isProvider, send } = HttpProvider;

const loadFixture = createFixtureLoader(provider.getWallets(), provider);

1
2
3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions