Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS - Calling a method from another method in 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 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?

like image 522
Veera Avatar asked Sep 05 '12 04:09

Veera


People also ask

How do you call a method in another method in JavaScript?

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.

How do I call a node js function from another file?

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.

CAN node JS run parallel?

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.


1 Answers

You can do it this way:

module.exports = {

  foo: function(req, res){

    bar();

  },
  bar: bar
}

function bar() {
  ...
}

No closure is needed.

like image 146
timidboy Avatar answered Oct 08 '22 19:10

timidboy