Search code examples
javascriptreusabilityobject-notation

JavaScript Object notation - using methods inside the same object?


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

}

Solution

  • 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);
        }
    
    }