在 Node.js 和 module.export 中调用类内部的本地方法

Nic*_*asN 0 node.js node-modules ecmascript-6 es6-class

所以我有一个类,其中一个函数依赖于另一个函数。该类与模块一起导出。根据我能找到的任何内容,我应该能够使用“this”,但这会引发错误。

例子:

class Test{

  test(){
    console.log('hello');
  }

  dependentMethod(){
    this.test();
  }
}

module.exports = Test;
Run Code Online (Sandbox Code Playgroud)

然而,这会在节点中引发这些错误:

(node:69278) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'test' of undefined
(node:69278) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:69278) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'test' of undefined
Run Code Online (Sandbox Code Playgroud)

如果我把这个函数放在类之外,它会工作得很好。谁能解释为什么会失败?:)

编辑:

这是 server.js 中使用该类的代码(针对示例进行了简化):

const test = require(__dirname + '/server/Test');


const validator = async function(req, res, next){

    const test = new test();
    const serverTest = await test.dependentMethod();
    next();

};

app.get('/Response/:id/:is/:userId/:hash', validator, async function (req, res, next) {
   //does smth
}
Run Code Online (Sandbox Code Playgroud)

单独使用也不起作用

const test = new Test();

app.get('/Response/:id/:is/:userId/:hash', Test.dependentMethod, async function (req, res, next) {
     //Same error
}
Run Code Online (Sandbox Code Playgroud)

Har*_*hah 5

按预期工作。

看看这里。您只需要纠正一些语法错误即可。

测试.js

class Test{

  test(){
    console.log('hello');
  }

  dependentMethod(){
    this.test();
  }
}

module.exports = Test;
Run Code Online (Sandbox Code Playgroud)

测试1.js

const fileR = require('./Test.js');

const validator = async function(){

 const fr = new fileR();
 const serverTest = await fr.dependentMethod();

};

validator();
Run Code Online (Sandbox Code Playgroud)

输出:

> hello
Run Code Online (Sandbox Code Playgroud)