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

Posted

技术标签:

【中文标题】我无法在课堂上正确访问此属性【英文标题】:I can't access to this property correctly on my class 【发布时间】:2021-09-29 05:08:20 【问题描述】:

为什么我无法在我的运行函数中访问this.name 属性?

基本事件类:

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.clientinstanceof 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);

【问题讨论】:

你怎么打电话给run?如果您将run 函数作为回调传递到某处,则需要将其绑定到类,以便其this 指向正确的this,例如。 foo(readyEvent.run.bind(readyEvent)) 而不是 foo(readyEvent.run) 另见:How does the "this" keyword work? 我添加了我如何注册要提问的事件。你能再检查一遍吗? 【参考方案1】:

evt.run 更改为evt.run.bind(evt),以便使用正确的this 调用函数。

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

【讨论】:

以上是关于我无法在课堂上正确访问此属性的主要内容,如果未能解决你的问题,请参考以下文章

如何在不使用API 的情况下访问Google课堂?

Google 课堂测试帐户无法访问云端硬盘

csharp 在课堂上获取所有属性

如何在课堂上保存最后一个ID?

对课堂上的会员访问火车感到困惑?

松软科技web课堂:字符串方法和属性