Typescript / MQTT / Node - 如何从回调函数访问 class 成员?

Typescript / MQTT / Node - How to acces class member from a callback function?

我正在制作一个应用来管理我家里的一些智能灯。

我创建了一个非常简单的 Broker class.

import * as aedes from 'aedes';
import * as net from 'net';

export class Broker {

    aedes: aedes.Aedes;
    broker: net.Server;
    port: number;

    constructor(port: number){
        this.aedes = aedes();
        this.broker = net.createServer(this.aedes.handle);
        this.port = port;
        this.broker.listen(this.port, () => {
            console.log('MQTT is listening.');
        });
    }
    
    /** 
     * This is a callback register function
     *
     * Callback function must have a signature of type : function(topic: string, payload: string)
     **/
    onMsgReceived(callback: {(topic: string, payload: string): void}){
        this.aedes.on('publish', (packet, client) => {
            if (packet.cmd != 'publish') return;
            callback(packet.topic, packet.payload.toString());
        });
    }

}

然后,例如 Test class.

export Test {
    someVar: string;
    
    constructor(){ }
    
    onMsgReceivedCallback(topic: string, payload: string){
        console.log('Hey, i\'m printed from the test class');
        console.log('And this is some var : ' + this.someVar);
    }
}

当然还有 index.ts 脚本。

import { Broker } from './broker.ts'
import { Test } from './test.ts'

const broker = new Broker(1883);
const test   = new Test();


broker.onMsgReceived(test.onMsgReceivedCallback);

问题是,如果在函数 test.onMsgReceived 中我想调用 class 的成员,例如 var someVar,节点会抛出以下错误:

TypeError: Cannot read property 'testVar' of undefined

我不明白如何解决这个错误... 你有什么想法吗?

如果您想将该方法作为回调传递,则必须将 class 实例的 this 上下文绑定到该方法。在 TypeScript 中有几种方法可以做到这一点。

使用箭头函数定义方法:

export Test {
    someVar: string;

    constructor() {}

    onMsgReceivedCallback = (topic: string, payload: string) => {
        console.log(`someVar: ${this.someVar}`);
    }
}

或者在构造函数中绑定方法:

export Test {
    someVar: string;

    constructor() {
        this.onMsgReceivedCallback = this.onMsgReceivedCallback.bind(this);
    }

    onMsgReceivedCallback(topic: string, payload: string) {
        console.log(`someVar: ${this.someVar}`);
    }
}