15

I have this nodeJS code.

module.exports = {

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

  bar: function(){
    ...
    ...
  }
}

I need to call the bar() method from inside the foo() method. I tried this.bar() as well as bar(), but both fail saying TypeError: Object #<Object> has no method 'bar()'.

How can I call one method from the other?

NikxDa
  • 4,137
  • 1
  • 26
  • 48
Veera
  • 32,532
  • 36
  • 98
  • 137

7 Answers7

14

You can do it this way:

module.exports = {

  foo: function(req, res){

    bar();

  },
  bar: bar
}

function bar() {
  ...
}

No closure is needed.

timidboy
  • 1,702
  • 1
  • 16
  • 27
9

The accepted response is wrong, you need to call the bar method from the current scope using the "this" keyword:

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

        this.bar();

      },
      bar: function() { console.log('bar'); }
    }
Nicolas Bonnici
  • 423
  • 4
  • 11
4

I think what you can do is bind the context before passing the callback.

something.registerCallback(module.exports.foo.bind(module.exports));
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
2

Try this:

module.exports = (function () {
    function realBar() {
        console.log('works');
    }
    return {

        foo: function(){
            realBar();
        },

        bar: realBar
    };
}());
Lucas Green
  • 3,951
  • 22
  • 27
1

Try the following code. You can refer each function from anywhere (needs to import .js file)

function foo(req,res){
    console.log("you are now in foo");
    bar();
}
exports.foo = foo;

function bar(){
    console.log("you are now in bar");
}
exports.bar = bar;
NikxDa
  • 4,137
  • 1
  • 26
  • 48
Chanaka Fernando
  • 2,176
  • 19
  • 19
0

Is bar intended to be internal (private) to foo?

module.exports = {
    foo: function(req, res){
        ...
        function bar() {
            ...
            ...
        }
        bar();     
        ...
    }
}
user323774
  • 400
  • 3
  • 9
0

in Node js + Express, you can use this syntax in the same controller

//myController.js
exports.funA = () =>{

    console.log("Hello from funA!")

    //cal funB
    funB()

}

let funB = () =>{

    console.log("Hello from funB!")
}

make sure to use the let keyword before the function and call it with the () parentheses inside the main function

OUTPUT

App listening at http://localhost:3000
Hello from fun A!
Hello from fun B!
Nassim
  • 2,879
  • 2
  • 37
  • 39