【问题标题】:ES6 class context in NodeJs? Or using 'this' inside a class in NodeJs?'NodeJs 中的 ES6 类上下文?或者在 NodeJs 的类中使用“this”?
【发布时间】: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


【解决方案1】:

问题的原因是你丢失了函数上下文

class UserController {
  async methodOne() {
    return this.methodTwo()
  }

  async methodTwo() {
    return Promise.resolve("methodtwo")
  }
}

const obj = new UserController();
const methodOne = obj.methodOne;

methodOne(); // ----> This will throw the Error

methodOne.call(obj); // ----> This Works

// Or you can call the method directly from the obj
obj.methodOne(); // Works!!

// If you want to cache the method in a variable and preserve its context use `bind()`
const methodOneBound = obj.methodOne.bind(obj);
methodOneBound(); // ----> This works

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 2016-01-16
    • 2020-04-12
    相关资源
    最近更新 更多