构建后“这个”丢失了吗? (TS /节点/表达)

时间:2017-03-30 12:25:10

标签: node.js express typescript constructor this

我正在尝试使用node-express构建一个简单的http应用程序。

设置路线时出现问题,MyRouter类的构造函数有this,但它在getRoutes()函数中丢失了。

class Main {
    public async run(): Promise<void> {
        const myRouter = new MyRouter(this.config);
        // this.server is express() during construct
        this.server.use("/v1", myRouter.getRoutes);

        await this.server.listen(this.config.rest.port);
    }
}


class MyRouter {
    private router: express.Router;

    constructor(private config: any) {
        this.router = express.Router();
        console.log(this); // Prints the whole Router object!
    }

    public getRoutes(): express.Router {
        console.log(this); // = "undefined" !
        this.router.use("/test", otherClass.getRoutes);
        return this.router;
    }
}

为什么会这样?

1 个答案:

答案 0 :(得分:2)

this的值不取决于它的定义位置,而取决于函数的调用方式。你这样做了:

this.server.use("/v1", myRouter.getRoutes);

这相当于:

var tmp = myRouter.getRoutes;

this.server.use("/v1", tmp); // `this` will refer to the global object

有两种解决方案。将其包装在匿名函数中以保留调用函数的对象:

this.server.use("/v1", function(){return myRouter.getRoutes()});

或使用.bind()

this.server.use("/v1", myRouter.getRoutes.bind(myRouter));