【发布时间】:2021-07-21 19:23:23
【问题描述】:
我有一个 typescript 类,其中包含我所有的快速页面函数,但是当我尝试使用 this 访问其类的成员变量时出现“未定义”错误:
class CPages {
private Version: string;
constructor(version: string) {
this.Version = version;
console.log(this.Version); // <- now 'this' refers to the class CPages. Output: 1.0
}
public async sendPage(req: express.Request, res: express.Response) {
console.log(this.Version); // <- now 'this' is undefined and so is this.Version. Output: Cannot read property 'Version' of undefined
res.render('page', {
version: this.Version
});
}
}
/* ... */
const Pages = new CPages("1.0");
App.get('/', Pages.sendPage);
我查看了箭头函数 (here) 的行为,似乎很相似。但与那里的示例不同,我既不能使用this 访问主程序也不能访问类。那么,如何在不将其作为参数发送的情况下访问版本变量呢?
ps:代码有点简化,App.get(...); 本身就在一个类中。
【问题讨论】:
-
当您执行
.get()绑定时,您的方法正在丢失其上下文。你可以使用App.get('/', Pages.sendPage.bind(Pages))来解决这个问题。
标签: javascript node.js typescript express