i experimenting with node.js and i have a set of methods that are being exported using module.exports however some of the methods are meant to be reusable with the same object but i am not sure how to go about this. In PHP i would simply reference this. I know this can be referenced in prototype objects, but can the same be done in JavaScript Object Notation?
Example code:
module.export = {
foo: (a, b) => {
return a + b;
},
bar: () => {
return foo(2, 5); // This is where i run into problems, using 'this' has no effect.
}
}
You can use the
thiskeyword in JavaScript. The only other change you will have to make is use actual functions instead of arrow functions, since arrow functions don't capturethisscope.Here is a quote from the MDN page on arrow functions.
Because it doesn't have its own
thisyou can't use arrow functions in this case.Below is an example of how you can refactor your code to work the way you are expecting.