【问题标题】:static variable in class is undefined in callback on app.listen类中的静态变量在 app.listen 的回调中未定义
【发布时间】:2017-05-06 18:56:03
【问题描述】:

我刚刚开始使用 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。 有人可以详细说明这是为什么吗?

【问题讨论】:

  • this.constructor.serverStartedCallback

标签: node.js express typescript


【解决方案1】:

来自"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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    相关资源
    最近更新 更多