类中的静态变量在app.listen的回调中未定义

时间:2017-05-06 10:14:30

标签: node.js express typescript

我刚开始使用打字稿而不是javascript来编写我的node.js个应用程序。我有点困惑。

我有这个启动快速服务器的代码

import * as express from 'express';

class Server {
    static expressApp: express.Express;
    static PORT: number = 3000;

    public static startServer():void {
        this.expressApp = express();
        console.log(this.PORT);
        this.expressApp.listen(this.PORT, this.serverStartedCallback)
    }

    private static serverStartedCallback():void {
        console.log("Server is listening on port " + this.PORT);
    }
}

Server.startServer();

我可以在startSever()中获取PORT变量的值。

但在回调serverStarted()中,this.PORT变量为undefined。 有人可以详细说明为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

来自"this parameters in callbacks"部分:

  

传递时,您还可以在回调中遇到this错误   函数到稍后将调用它们的库。因为图书馆   调用你的回调会把它称为普通函数, this   将是未定义的。

使用类名传递函数而不是使用this的最简单的修复:

this.expressApp.listen(Server.PORT, Server.serverStartedCallback)

注意:在非静态环境中,使用箭头功能可以轻松解决此问题。

class Caller {
    call(method: () => void) { method(); }
}

class Server {
    caller: Caller = new Caller();
    PORT: number = 3000;

    public startServer(): void {
        this.caller.call(this.serverStartedCallback_Arrow);
        this.caller.call(this.serverStartedCallback_NonArrow);
    }

    private serverStartedCallback_Arrow = () => {
        console.log("Arrow Server is listening on port " + this.PORT);
    }

    private serverStartedCallback_NonArrow(): void {
        console.log("Nonarrow Server is listening on port " + this.PORT);
    }
}

var server = new Server();
server.startServer();

控制台:

Arrow Server is listening on port 3000
Nonarrow Server is listening on port undefined