0

Why I can't access this.name property in my run function?

Base event class:

import { ClientEvents } from 'discord.js';

import DiscordClient from './DiscordClient';

export default abstract class Event {
    readonly client: DiscordClient;
    readonly name: keyof ClientEvents | "raw";

    constructor(client: DiscordClient, name: keyof ClientEvents | "raw") {
        this.client = client;
        this.name = name;
    }

    /**
     * Runs the event.
     * @param params Parameters
     */
    abstract run(...params: any | undefined): Promise<void>;
}

Example event class:

import DiscordClient from '../structures/DiscordClient';
import Event from '../structures/Event';

export default class ReadyEvent extends Event {

    constructor(client: DiscordClient) {
        super(client, "ready");
        console.log(this.name); // Output: ready
    }

    async run() {
        console.log(this.name); // Output: undefined
    }

}

I am registering events like that: (this.client instanceof DiscordClient)

/**
 * Registers single event.
 * @param event Event
 */
private registerEvent(event: any) {
    if (isConstructor(event, Event)) event = new event(this.client);
    else if (isConstructor(event.default, Event)) event = new event.default(this.client);
    if (!(event instanceof Event)) throw new Error(`Invalid event object to register: ${event}`);

    const evt = event as Event;

    if (this.events.some(e => e.name === evt.name)) throw new Error(`A event with the name "${evt.name}" is already registered.`);

    this.events.set(evt.name, evt);
    this.client.on(evt.name as keyof ClientEvents, evt.run);
}
BurakBey
  • 55
  • 5
  • 3
    How are you calling `run`? If you pass the `run` function as a callback somewhere, you'll need to bind it to the class so that its `this` points to the correct `this`, eg. `foo(readyEvent.run.bind(readyEvent))` instead of `foo(readyEvent.run)` – cbr Jul 21 '21 at 20:27
  • See also: [How does the "this" keyword work?](https://stackoverflow.com/q/3127429/996081) – cbr Jul 21 '21 at 20:32
  • I added how i register events to question. Can you check it again? – BurakBey Jul 21 '21 at 20:38

1 Answers1

1

Change evt.run to evt.run.bind(evt) so that the function is called with the correct this.

See also How does the "this" keyword work?"

cbr
  • 12,563
  • 3
  • 38
  • 63