Node JS - 从同一文件中的另一个方法调用方法

Vee*_*era 14 javascript node.js

我有这个nodeJS代码.

module.exports = {

  foo: function(req, res){
    ...
    this.bar(); // failing
    bar(); // failing
    ...
  },

  bar: function(){
    ...
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要bar()从方法内部调用foo()方法.我想 this.bar()还有bar(),但都失败说TypeError: Object #<Object> has no method 'bar()'.

我如何从另一个方法调用一个方法?

tim*_*boy 10

这样做:

module.exports = {

  foo: function(req, res){

    bar();

  },
  bar: bar
}

function bar() {
  ...
}
Run Code Online (Sandbox Code Playgroud)

不需要关闭.


Nic*_*ici 7

接受的响应是错误的,您需要使用“ this”关键字从当前范围调用bar方法:

    module.exports = {
      foo: function(req, res){

        this.bar();

      },
      bar: function() { console.log('bar'); }
    }
Run Code Online (Sandbox Code Playgroud)