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 :)