0

I'm trying to understand why this works:

let user = {
  name: 'John',
  age: 30,
  sayHi() {
    console.log(this.name); // works. This defined.
  }
}

But the 'this' value here is undefined:

  const testRoutes = [
    {
      path: '/home',
      exact: true,
      isPrivate: true,
      header: (
        <span>
          <i className='fas fa-home' />
          &nbsp; Home
        </span>
      ),
      main() {
        console.log(this); // undefined
      },
    },
  ];

Update

Okay, so I figured out the problem was that I was destructuring the object arguments.

Destructuring the object and calling main results in an undefined this:

  testRoutes.map(({ path, exact, isPrivate, main }) => {
    main(); // undefined
  });

But this works as expected:

  testRoutes.map(route => {
    route.main(); // this is defined
  });

I still find this very bizarre and would like to understand why this is happening.

ram
  • 528
  • 2
  • 11
  • 1
    `this` changes depending on how the function is called. How is it called? – evolutionxbox Aug 04 '20 at 15:23
  • FYI: I've found *this* to be frustrating in this way too, so I stopped using it whenever possible. – ControlAltDel Aug 04 '20 at 15:25
  • @evolutionxbox I think you're right. The component is being called with with Route from react-router-dom. When I just map through and call main() it works. – ram Aug 04 '20 at 17:11

0 Answers0