[英]I can't access to this property correctly on my class
Why I can't access this.name
property in my run function?为什么我无法在运行函数中访问
this.name
属性?
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)我正在注册这样的事件:(
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
.更改
evt.run
到evt.run.bind(evt)
这样函数被调用正确this
。
See also How does the "this" keyword work?"另请参阅“this”关键字如何工作?”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.