即使在使用箭头function的情况下,“这”在打字稿中也是未定义的

当我收到'catch'callback时,'this'是未定义的,即使使用箭头function。 有任何想法吗?

private all(req: Request, res: Response): void { EntityRepository.getRepositoty(req.params.etName).then(repo => { ... }).catch((err) => { this.handleError(res, err); // here I get undefined. }); } 

如何调用所有的func。

它被称为基于快速路线。

添加了@ jfriend00build议的方法bind

 constructor() { // Connect to database. DataAccess.connect(); // Starts configuring routes for api this.router = Router(); // Bad request due to absence of entity type. this.router.get("/", (req, res) => { res.statusCode = 400; res.statusMessage = SysMsgs.error.noEntityTypeSpecified.message; res.send(); }); // Added method 'bind'. this.router.get(this.routeBase, this.all.bind(this)); this.router.get(this.routeBase + "/:id", this.findOne.bind(this)); } 

使用箭头函数, this将保留它在箭头函数调用之前的范围内的值。 在你的情况下,这意味着它将在你all函数开始时具有任何价值。 所以,这个值取决于如何调用all函数。

而且,根据你的this.router.get()指定this.all作为callbackthis.all ,这意味着this内部this.all将被设置为Express在调用callbackthis.all时设置的值。 而且,这是undefined

你可以通过使用.bind()来解决你的问题。

  this.router.get(this.routeBase, this.all.bind(this)); 

这将确保在.all()运行时设置适当的值。 然后, all() arrow函数将使用这个值。

注意:您将需要使用.bind()作为callback传递的任何方法,您希望this是callback中的对象。 当你传递这样的东西时,这个值会丢失,只传递给方法的引用。 调用者然后调用该方法作为一个正常的function,没有对象绑定。 你使用.bind()来控制你自己。 .bind()本质上创build了一个小存根函数,通过调用你的方法来重新附加适当的指针。


你也可以为它创build自己的包装箭头function:

  this.router.get(this.routeBase, (req, res) => this.all(req, res)); 

正如Saravana指出的那样,将保留TypeScripttypes检查。

虽然@ jfriend00的回答覆盖了你的代码的问题,在JavaScript中使用bind没有任何问题,但是当你在TypeScript中使用bind时候有一点问题。 bind的types签名是:

 bind(this: Function, thisArg: any, ...argArray: any[]): any; 

注意, bind返回any意义closures返回的函数的任何types检查,这会导致微妙的错误。 以下面的例子为例:

 // Assume the definition for `router.get` is something similar to this: get(routeBase: string, callback: (req: Request, resp: Response) => void) // ... and in the place you are calling it private all(param: number): void { } this.route.get(this.routeBase, this.all.bind(this)); // No compiler error, but `all` and the callback parameter expected by `route.get` don't match! 

如果你想保持types检查,你可以使用下面的东西,而不是bind

 this.route.get((req, resp) => this.all(req, resp)); 

请参阅: https : //github.com/Microsoft/TypeScript/issues/212