“这个”在构造之后丢失了? (TS /节点/expression)
我正在尝试使用node-express构build一个简单的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; } }
为什么是这样?
这个值不取决于定义的位置,而是取决于函数的调用方式。 你做到了这一点:
this.server.use("/v1", myRouter.getRoutes);
这相当于:
var tmp = myRouter.getRoutes; this.server.use("/v1", tmp); // `this` will refer to the global object
有两个解决scheme。 要么将其包装在匿名函数中以保留调用该函数的对象:
this.server.use("/v1", function(){return myRouter.getRoutes()});
或者使用.bind()
this.server.use("/v1", myRouter.getRoutes.bind(myRouter));