I have this Node JS code.
module.exports = {
foo: function(req, res){
...
this.bar(); // failing
bar(); // failing
...
},
bar: function(){
...
...
}
}
I need to call the bar()
method from inside foo()
. Tried, this.bar()
and bar()
but both failing saying TypeError: Object # has no method 'bar()'.
So, how can I call one method from the other?
Do it this way:
module.exports = {
foo: function(req, res){
bar();
},
bar: bar
}
function bar() {
...
}
No closure is needed.
I think what you can do is bind the context before passing the callback.
something.registerCallback(module.exports.foo.bind(module.exports));
Try this:
module.exports = (function () {
function realBar() {
console.log('works');
}
return {
foo: function(){
realBar();
},
bar: realBar
};
}());
Is bar intended to be internal (private) to foo?
module.exports = {
foo: function(req, res){
...
function bar() {
...
...
}
bar();
...
}
}