COVID19 Lockdown Dev Log – Day 23, ‘This’ And JavaScript Methods

What I Worked On

NodeJs Notes app

What I Learned

Writing a method for a JavaScript object is best done by using the “normal” JavaScript function declaration like so:

const event = {
  title: 'Attend The Cinema',
  listParticipants() {
    console.log('Participants going to ' + this.title);
  }
}

But why not use an arrow-function in this case? That’s the new thing, right? All I would have to do is write it like this:

const event = {
  title: 'Attend The Cinema',
  listParticipants: () => {
    console.log('Participants going to ' + this.title);
  }
}

This will give the output:

Participants going to undefined

Why? Well, a ‘normal’ function/method in a JavaScript object binds its own ‘this’, which in this case refers to the ‘event’ object. This is why I can write ‘this.name’ in the first example.

Arrow functions/methods do not bind their own ‘this’, so I do not have access to the ‘title’ property of the object thereby outputting ‘undefined’. Why don’t they do that though? Let me demonstrate by building on our two examples above. I add an array of names (participants) and a foreach loop:

const event = {
  title: 'Attend The Cinema',
  participants: ['Andrew', 'Tina', 'Nikolaj'],
  listParticipants() {
    this.participants.forEach(function (participant) {
      console.log(participant + ' is attending ' + this.title);
    })
  }
}

The output will result in this:

Andrew is attending undefined
Tina is attending undefined
Nikolaj is attending undefined

This happens because the function binds its own ‘this’. Here that is a problem so in comes the arrow-function to save the day!:

const event = {
  title: 'Attend The Cinema',
  participants: ['Andrew', 'Tina', 'Nikolaj'],
  listParticipants() {
    this.participants.forEach(( participant ) => {
      console.log(participant + ' is attending ' + this.title);
    })
  }
}

Now, because the arrow-function doesn’t make its own ‘this’ binding, I can access the ‘this.title’ in the ‘event’ object 😀

What Distracted Me During The Day

  • GF needed help for proofreading an assignment
  • Snapchat

Resources