Reputation: 33182
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?
Upvotes: 15
Views: 24853
Reputation: 1722
You can do it this way:
module.exports = {
foo: function(req, res){
bar();
},
bar: bar
}
function bar() {
...
}
No closure is needed.
Upvotes: 14
Reputation: 2876
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!
Upvotes: 0
Reputation: 460
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'); }
}
Upvotes: 11
Reputation: 2335
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;
Upvotes: 1
Reputation: 430
Is bar intended to be internal (private) to foo?
module.exports = {
foo: function(req, res){
...
function bar() {
...
...
}
bar();
...
}
}
Upvotes: 1
Reputation: 3959
Try this:
module.exports = (function () {
function realBar() {
console.log('works');
}
return {
foo: function(){
realBar();
},
bar: realBar
};
}());
Upvotes: 2
Reputation: 78262
I think what you can do is bind the context before passing the callback.
something.registerCallback(module.exports.foo.bind(module.exports));
Upvotes: 4