【发布时间】:2018-08-13 09:27:20
【问题描述】:
我是 node js 的新手,实际上我无法理解如何在类中调用方法,除非是静态调用或每次迭代函数时创建一个新对象。
这有点疯狂。例如:
class UserController
{
methodOne (req, res) {
this.methodTwo (req);
}
methodTwo (data) {
return data;
}
}
这就是我想要调用我的函数的方式,但是每次我这样做时,我都会得到 this 未定义的错误。
我知道fat arrow functions 不像在 javascript 中那样遵循相同的上下文。但我只是想确定我是否做得对。
这就是我实现上述代码的方式。
class UserController
{
static methodOne (req, res) {
UserController.methodTwo (req);
}
static methodTwo (data) {
// Manipulates request before calling
return UserController.methodThree (data);
}
static methodThree (data) {
return data;
}
}
即使用类名UserController 静态调用每个方法。
所以如果有更好的方法,我需要你提出建议。 提前致谢。
PS:以上代码只是示例。
【问题讨论】:
-
但它不起作用,因为
this未定义。 IDK 如何将this绑定到这个类。 -
没有。我只是在单个类中迭代方法。没有继承,什么都没有。
-
如果函数的主体中没有
await关键字,则无需在函数声明中使用async关键字。 -
这只是一个例子。
-
async和你的问题完全无关,何必把事情复杂化?
标签: javascript node.js ecmascript-6 async-await static-methods