Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
philipjonsen opened this issue Sep 13, 2023 · 0 comments

Comments

@philipjonsen
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
1 participant