0

I'm trying to add a property to an object using a method. Here is the code:

const siddhu = {
    name: 'Siddhu',
    friends: ['Dylan', 'Jordans', 'Aathi'],
    setBestFriend: () => this.bestFriend = this.friends[0],
    setNumOfFriends: () => this.numOfFriends = this.friends.length,
}
siddhu.setBestFriend()
siddhu.setNumOfFriends()

console.log(`${siddhu.name} has ${siddhu.numOfFriends} friends, and his best friend is ${siddhu.bestFriend}`);

For some reason, this doesn't work. I know that changing the this keyword to siddhu fixes the problem, but this isn't ideal, as I want to be able to copy-paste this code multiple times, and I would have to change siddhu every time I did.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Also see [MDN Creating new objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#creating_new_objects) which shows how to create a custom object which you can reuse multiple times. – Yogi Oct 01 '22 at 10:42

1 Answers1

0

No problem - apparently you can't use this with arrow functions because then this would reference the arrow function. All credit goes to jonrsharpe for telling me!