0

I have a collection of helper-functions, like this:

var myHelpers = {

    addFoo: ( name ) => {
        return name + 'foo';
    },

    addFooBar: ( name ) => {
        return this.addFoo( name ) + 'bar'; // This is what throws the error.
    }

}

window.myHelpers = myHelpers;
export default myHelpers;

And I then use it like this:

import myHelpers from "./myHelpers";

let test = 'abc';
test = myHelpers.addFooBar( test );

But this throws the error: Uncaught TypeError: Cannot read properties of undefined

... How do I make these functions call eachother, without getting this error?

Zeth
  • 2,273
  • 4
  • 43
  • 91
  • Use a regular function instead of an arrow function – Reyno Oct 28 '21 at 13:46
  • _Use a regular function instead of an arrow function..._ Can you please explain why? @Reyno – B001ᛦ Oct 28 '21 at 13:53
  • @B001ᛦ There is a duplicate answer which explains this very well. But here is an (extremely short) explanation: normal functions redefine `this` while arrow functions do not – Reyno Oct 28 '21 at 14:02

1 Answers1

1

Use myHelpers instead of this

addFooBar: name => {
  return myHelpers.addFoo(name) + 'bar'
},
aerial
  • 1,188
  • 3
  • 7
  • 15