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.