gpt4 book ai didi

node.js - "this"构建后丢失? (ts/Node/express)

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:46 25 4
gpt4 key购买 nike

我正在尝试使用 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;
}
}

这是为什么?

最佳答案

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));

关于node.js - "this"构建后丢失? (ts/Node/express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com