分享
三行代码  ›  专栏  ›  技术社区  ›  BurakBey

我无法在类上正确访问此属性

  •  0
  • BurakBey  · 技术社区  · 5 天前

    this.name 我的run函数中的属性?

    基本事件类:

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

    事件类示例:

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

    我正在注册这样的事件:( this.client

    /**
     * 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);
    }
    
    1 回复  |  直到 5 天前
        1
  •  1
  •   cbr    5 天前

    改变 evt.run evt.run.bind(evt) 以便使用正确的 this .

    另请参见 How does the "this" keyword work?"