2

If you try running this JS snippet,

module.exports = {
  add: function(a, b) { return a + b; },
  subtract: function(a, b) { return add(a, -b); }
}

you'll get an error, saying that add is undefined. The same applies here:

module.exports = {
  add: function(a, b) { return a + b; },
  sums: {
    two_and_three: add(2,3);
  }
}

What is the best way to call a previously mentioned function in this way?

James Faulcon
  • 733
  • 2
  • 6
  • 8

3 Answers3

4

You should use this as indicated below:

module.exports = {
  add: function(a, b) { return a + b; },
  subtract: function(a, b) { return this.add(a, -b); }
}

For your second use case you need something like this:

module.exports = {
  add: function(a, b) { return a + b; },
  sums: {
    two_and_three: function() { return module.exports.add(2,3); }
  }
}
Wagner DosAnjos
  • 6,304
  • 1
  • 15
  • 29
1

Understanding various JS function invocation patterns would help here:

How the function is called, decides the function's context, which is accessible using 'this' keyword inside the function.

Now coming to your code:

module.exports = {
  add: function(a, b) { return a + b; },
  subtract: function(a, b) { return add(a, -b); }
}

We would call the subtract function in the following way:

module.exports.subtract(1, 3);

Method invocation pattern is used here. Which means that this inside the subtract function would refer to substract's parent object (module.exports), which also contains the add function. Hence, the add function can be accessed using this.add inside the subtract function, like this:

module.exports = {
  add: function(a, b) { return a + b; },
  subtract: function(a, b) { return this.add(a, -b); }
}

For the second case, you can use wdosanjos's answer, if having sums.two_and_three as a function works for you, or if you need sums as the results, this can be done:

module.exports = {
    add: function(a, b) { return a + b; }
};

module.exports.sums = {
    two_and_three: module.exports.add(2,3),
    three_and_four: module.exports.add(3,4)
};

Or, there are some other ways suggested here, for accessing parent object's siblings/properties.

Hope this helps :)

Community
  • 1
  • 1
Aditya Singh
  • 116
  • 5
-1
module.exports = {
   add: function(a, b) { return a + b; },

   subtract: function(a, b) { return this.add(a, -b); }
 }
shaish
  • 1,479
  • 1
  • 12
  • 23