我从 Typescript 开始,但在从同一类的另一个方法调用一个方法时遇到问题。
读到这个问题时,有些人说在方法名称之前使用“this”,但是,在我的例子中它不起作用。
class PlaylistController {
public async create(req: Request, res: Response): Promise<Response> {
let artists = req.body.bands;
artists = artists.split(',');
const search = await Object.values(artists).map(
(artistsName: string): void => this.searchArtists(artistsName),
);
return res.json(search);
}
private searchArtists = (artistName: string): void => {
console.log(artistName);
};
}
export default new PlaylistController();
编辑: 这是我用来调用我的方法的代码:
class App {
public express: express.Application;
public constructor() {
this.express = express();
this.middlewares();
this.routes();
}
private middlewares(): void {
this.express.use(express.json());
}
private routes(): void {
this.express.get('/', (req, res): void => {
res.send('API Rodando...');
});
this.express.post('/createPlaylist', PlaylistController.create);
}
}
export default new App().express;
当我执行此代码时,不会调用方法“searchArtists”,并且出现错误:
UnhandledPromiseRejectionWarning:类型错误:无法读取未定义的属性“searchArtists”。 ( Node :11941)UnhandledPromiseRejectionWarning:未处理的 promise 拒绝。此错误的根源是在没有 catch block 的情况下抛出异步函数内部,或者拒绝未使用 .catch() 处理的 Promise。 (拒绝 ID:1) ( Node :11941)[DEP0018] DeprecationWarning:未处理的 promise 拒绝已被弃用。将来,未处理的 Promise 拒绝将会以非零退出代码终止 Node.js 进程。
所以,我不知道我做错了什么,希望你能帮助我。
最佳答案
您已将第二个参数处看似未绑定(bind)的方法 PlaylistController.create
传递给 this.express.post()
。我假设 post()
的主体最终实际上调用了未绑定(bind)的方法,您的问题是它已经丢失了原始的 this
上下文,并且您收到了该错误。 Passing around unbound methods is usually a mistake :
const x = {
a() { console.log("a"); },
b() { this.a(); }
};
这里,x
是一个具有 a
和 b
方法的对象。 b
方法调用 this.a()
。如果您直接将 b
作为 x
的方法调用,则一切都会按您的预期运行:
x.b(); // calling b as a property of x: "a"
但是如果将 x.b
方法保存到新变量(或将其传递到函数参数等):
const xb = x.b; // xb is the b method of x, but it is not bound to x any longer.
您不能再直接调用它:
try {
xb(); // error at runtime: this is undefined
} catch (e) {
console.log(e); // "TypeError, this is undefined"
}
xb()
调用会给您带来运行时错误,因为当您直接调用函数而不是在其他对象的属性上下文中时,this
上下文将是未定义
。
幸运的是,这可以通过使用函数对象的 bind()
方法来修复:
const xbBound = xb.bind(x); // explicitly bind the method to x again
xbBound(); // "a"
<小时/>
因此,对于您的情况,我会尝试将 PlaylistController.create
方法重新绑定(bind)到 PlaylistController
对象:
this.express.post('/createPlaylist', PlaylistController.create.bind(PlaylistController));
看看是否有效。好的,希望有帮助;祝你好运!
关于javascript - 从 Typescript 中同一类的另一个方法调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57243321/