简体   繁体   中英

I can't access to this property correctly on my class

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);
}

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?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM