首页 > 解决方案 > 打字稿设置功能成员和使用这个

问题描述

我正在使用打字稿开发一个电子应用程序。我的 main.ts 创建了我自己的 CommunicationProvider 类的对象。我想让这个类声明几个方法(在它正在实现的接口中定义),但在我的 main.ts 中设置这些方法的实际实现。所以我宣布我的班级为:

export class SocketIOInterceptionProvider implements IInterceptionProvider {

// IInterfaceProvider methods
show: (x?: number, y?: number) => void;
hide: () => void;
move: (x: number, y: number) => void;

constructor(port: number = 3000) {

    this.initHttpServer(port);

}

public initHttpServer(port: number): void {

    this._express.get('/show', function(req, res) {
        console.log('SHOW from ' + req.ip);
        if (this.show) this.show();    
    });
}   

}

在 main.ts 我设置了实现:

const provider: SocketIOInterceptionProvider = new 
SocketIOInterceptionProvider();

provider.show = (x?: number, y?: number) => { //show electron win}

在运行时 - 我的函数没有被触发,因为 'this' 未定义,当我点击:

if (this.show) this.show(); 

我怎样才能保持“这个”?是否有任何其他推荐的方式来处理来自 TS 类的事件?

标签: typescriptelectronthis

解决方案


'this' 在快速回调中丢失了,所以我将它分配给一个局部变量以在快速回调中使用:

public initHttpServer(port: number): void {

    this._express = express();
    this._httpServer = this._express.listen(port);
    const provider=this;

    this._express.get('/show', function(req, res) {
        console.log('SHOW from ' + req.ip);
        if (provider.show) provider.show();    
    });

推荐阅读