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' />
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.