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?
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.
While it's not possible to run two pieces of JavaScript at the same time that would have access to shared JS objects, there are few ways you can run isolated JavaScript computations in parallel. To achieve this, you can launch multiple node processes or child processes using the cluster module.
You can do it this way:
module.exports = {
foo: function(req, res){
bar();
},
bar: bar
}
function bar() {
...
}
No closure is needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With