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

问题描述 投票:-2回答:2

所以我有一个具有函数的类,其中一个依赖于另一个。此类与模块一起导出。根据我能找到的任何东西,我应该能够使用“this”但是会抛出错误。

例:

class Test{

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

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

module.exports = Test;

但是,这会在节点中抛出这些错误:

(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

如果我把这个函数放在课外,它会正常工作。谁能解释为什么这会失败? :)

编辑:

这是使用该类的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
}

单独使用也不起作用

const test = new Test();

app.get('/Response/:id/:is/:userId/:hash', Test.dependentMethod, async function (req, res, next) {
     //Same error
}
node.js ecmascript-6 node-modules es6-class
2个回答
1
投票

按预期工作。

看看这里。你只需要纠正一些语法错误。

Test.js

class Test{

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

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

module.exports = Test;

Test1.js

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

const validator = async function(){

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

};

validator();

输出:

> hello

1
投票

伙计,你没有向我们展示真实的代码。

我觉得在现实生活中你使用test.dependentMethod作为中间件。它很容易使用独立功能来消除上下文。这就是为什么你有一个错误Cannot read property 'test' of undefined

解决方案是使用test.dependentMethod.bind(test)或编辑部分中的代码,您可以在其中创建单独的验证器函数并正确使用类实例。

© www.soinside.com 2019 - 2024. All rights reserved.