0

In my code I'm creating a new anonymous class that is implementing an interface.

private service: CommandService;

this.command = new class implements Command {
  execute(id: string): Promise<Result> {
    const resultId: string = await this.service.getResultId();
    return await this.service.getResult(resultId);
  };
};

What would be the best way to access the service in this case? I'm thinking of either

  • define const _this = this above the class.
  • give the service to the execute function.

Is there a better way to achieve this?

Edit:

I know that there's a wonderful answer here already, however, it doesn't explain how to access this within an anonymous class.

moritzg
  • 4,266
  • 3
  • 37
  • 62
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Heretic Monkey Jun 03 '19 at 12:59
  • @HereticMonkey Please see my edit. – moritzg Jun 03 '19 at 13:09
  • The essence of the answers will be the same; set a variable to `this` outside the callback; pass the instance to the callback as the `thisArg` to `call` or `apply`, etc. – Heretic Monkey Jun 03 '19 at 13:23

1 Answers1

0

You never want to assign this. to a variable, that kind of breaks the whole point of using classes. This should instead be 2 diffrent classes, and just pass the needed values into the "inner" class, like this

import { Command, CommandService, Result } from 'foo';

class MyCommand implements Command {
    constructor(private readonly service: CommandService) { }
    async execute(id: string): Promise<Result> {
        const resultId: string = await this.service.getResultId();
        return await this.service.getResult(resultId);
    };
};

class ParentClass {
    private readonly service: CommandService;
    private readonly command = new MyCommand(this.service); 
}
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
  • "You never want to assign `this` to a variable, that kind of breaks the whole point of using classes." Why? Is that just your opinion or do you have some source that corroborates this? – jcalz Jun 03 '19 at 15:46
  • For example, I'm not sure what's wrong with [either of these solutions](https://stackblitz.com/edit/typescript-wixfgd?file=index.ts) or how one or both is "breaking" classes. – jcalz Jun 03 '19 at 16:00
  • @jcalz Wondering about the same thing. – moritzg Jun 04 '19 at 07:21
  • Sure it can be done and it works, but it just seems overly complex. Perhaps "breaking" was the wrong word choice, I apologize for that. Ideally (to me anyway) you want a single class per file. Define each class separately and then call new instances of them instead of creating entirely new classes. `new MyCommand()` instead of `(new class implements Command { ... } )()` and then having to pass contexts around. – Chris Barr Jun 04 '19 at 12:56