0

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.
    }

}
Frederick M. Rogers
  • 841
  • 4
  • 14
  • 37

1 Answers1

2

You can use the this keyword in JavaScript. The only other change you will have to make is use actual functions instead of arrow functions, since arrow functions don't capture this scope.

Here is a quote from the MDN page on arrow functions.

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.

Because it doesn't have its own this you 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.

module.export = {

    foo: function (a, b) {
        return a + b;
    },

    bar: function () {
       return this.foo(2, 5);
    }

}
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179
  • Actually, short-hand methods would be closer to the use-case here: `foo(a, b){ return a + b; }, bar(){ return this.foo(2, 5) }`, since those behave similarly to arrow functions but also have their own `this`. – Sebastian Simon Jul 18 '18 at 18:33
  • Thanks for the clarification. Having had ES6 hammered into my skull along with arrow functions i just assumed that it would function the same way. Now i am not so sure it is worth saving the extra few characters. – Frederick M. Rogers Jul 18 '18 at 18:34
  • @Xufox, are you saying that you can omit the method key/name is this case ? as in foo: function() {} can be written just foo() {} ? – Frederick M. Rogers Jul 18 '18 at 18:36
  • @FrederickM.Rogers Yes. It’s [short-hand method notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015). They are, like arrow functions, not constructible (cannot be `new`’d). – Sebastian Simon Jul 18 '18 at 18:37