Node JS - calling a method from another method in the same file

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 the foo() method. I tried this.bar() as well as bar() , but both refused to say TypeError: Object #<Object> has no method 'bar()' .

How can I call one method from another?

+7
source share
6 answers

Do it like this:

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

Closing is not required.

+4
source

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

 something.registerCallback(module.exports.foo.bind(module.exports)); 
+1
source

Try the following:

 module.exports = (function () { function realBar() { console.log('works'); } return { foo: function(){ realBar(); }, bar: realBar }; }()); 
+1
source

The accepted answer is incorrect, you need to call the bar method from the current area using the keyword "this":

  module.exports = { foo: function(req, res){ this.bar(); }, bar: function() { console.log('bar'); } } 
+1
source

Is a bar intended for internal (private) to foo?

 module.exports = { foo: function(req, res){ ... function bar() { ... ... } bar(); ... } } 
0
source

Try using the following code. You can send each function from anywhere (you need to import the .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; 
0
source

All Articles