0

I'm following a tutorial on Javascript and ES6 and in the example below I get an error:

"TypeError: Cannot read property 'teamName' of undefined."

The tutor explains it as: "Whenever we pass an anonymous function somewhere in our code base, the value of this inside of that function is lost!" What does he mean by that? Shouldn't this hold the object making the call and wouldn't that mean team.teamName which would return Avengers here? I'm confused. Also, how is the issue fixed when we use .bind(this)?

const team = {
 members: ['Tony', 'Peter'],
 teamName: 'Avengers',
 teamSummary: function() {
    return this.members.map(function(member) {

    return `${member} is a member of ${this.teamName}`;

  });

 }

};

team.teamSummary();
RBT
  • 18,275
  • 13
  • 127
  • 181
Bikal Nepal
  • 367
  • 4
  • 18

1 Answers1

0

Use arrow function (=>) like as shown below. They help in retaining the this that called the function.

const team = {
 members: ['Tony', 'Peter'],
 teamName: 'Avengers',
 teamSummary: function() {
    return this.members.map((member) => {

    return `${member} is a member of ${this.teamName}`;

  });

 }

};

team.teamSummary();

Please read this blog for more fixes for the same solution

Nandita Sharma
  • 12,347
  • 2
  • 14
  • 26