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
  • 24,161
  • 21
  • 159
  • 240
Bikal Nepal
  • 477
  • 1
  • 10
  • 26
  • `function(member) {` <- this function has a new context – Jonas Wilms May 24 '18 at 05:48
  • I hope the duplicates provide an understandable explanation, if you still got questions feel free to ask :) – Jonas Wilms May 24 '18 at 05:51
  • *"Shouldn't `this` hold the object making the call"* but in a context like `somefunction(callback){ ... callback(); }` what is the object that is making the call to `callback()`? – Thomas May 24 '18 at 05:51

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
  • 13,287
  • 2
  • 22
  • 35