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()' .
bar()
foo()
this.bar()
TypeError: Object #<Object> has no method 'bar()'
How can I call one method from another?
Do it like this:
module.exports = { foo: function(req, res){ bar(); }, bar: bar } function bar() { ... }
Closing is not required.
I think you can do a bind context before passing the callback.
something.registerCallback(module.exports.foo.bind(module.exports));
Try the following:
module.exports = (function () { function realBar() { console.log('works'); } return { foo: function(){ realBar(); }, bar: realBar }; }());
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'); } }
Is a bar intended for internal (private) to foo?
module.exports = { foo: function(req, res){ ... function bar() { ... ... } bar(); ... } }
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;