0
export default {
 one: () => {
  //some codes
 },
 two: () => {
  //some codes
  one(); // error
  this.one(); // error
 }
}

I have module like that, and I want to call function one() inside function two().
But I got error like this : TypeError: Cannot read property 'one' of undefined.
How can I fix it? I want to know the cause.

hello
  • 131
  • 1
  • 10
  • 1
    Extract them out into separate functions and then include them in the export? – evolutionxbox Jul 26 '21 at 14:42
  • 1
    "*I want to know the cause.*" see [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/q/31095710) and for a more general overview: [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/q/34361379) + [Self-references in object literals / initializers](https://stackoverflow.com/q/4616202) – VLAZ Jul 26 '21 at 14:44

2 Answers2

2

What about extracting them out into separate functions and then include them in the export?

const one = () => {
  //some codes
};

const two = () => {
  //some codes
  one();
};

export default {
 one,
 two
}
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
2

You shouldn´t use arrows function if you want to give a new context to the this keyword.

Look this example, it uses an arrow function in the two method. It would return error since the this keyword is not related to the object, but mantains the context from the last function.

let obj = {
  one: function() {
    console.log("one");
  },
  two: () => {     // Arrow function
   this.one();
  }
}

obj.two();

If you use a normal function, the this keyword would be related to the object:

let obj = {
  one: function() {
    console.log("one");
  },
  two: function() {     // Normal function
   this.one();
  }
}

obj.two();

This is the main difference between arrow functions and normal functions

AlexSp3
  • 2,201
  • 2
  • 7
  • 24