When we use an anonymous function inside a class, the variable ‘this’ will be reported as undefined as in the following example:
const department ={
employees:['Laura','Robert','Kevin'],
manager: 'John',
summary: function(){
return this.employees.map(function(employee){
return `${employee} reports to ${this.manager}`;
});
}
};
console.log(department.summary()); // Cannot read property manager of undefined
Option 1: Using function.bind(this)
In the highlighted line, we provide binding of ‘this’ to the anonymous function:
const department ={
employees:['Laura','Robert','Kevin'],
manager: 'John',
summary: function(){
return this.employees.map(function(employee){
return `${employee} reports to ${this.manager}`;
}.bind(this));
}
};
console.log(department.summary());
Option 2: Assigning ‘this’ to a variable within the scope of the anonymous function
In this case ‘this’ is assigned to a variable self and the anonymous function refers to self.manager instead of this.manager:
const department2 ={
employees:['Laura','Robert','Kevin'],
manager: 'John',
summary: function(){
var self = this;
return this.employees.map(function(employee){
return `${employee} reports to ${self.manager}`;
});
}
};
console.log(department2.summary());
Option 3: Using an arrow function
When you define the anonymous function using the arrow notation, an implicit binding will take place, which is equivallent to Option 1 above.
const department3 ={
employees:['Laura','Robert','Kevin'],
manager: 'John',
summary: function(){
return this.employees.map((employee)=>{
return `${employee} reports to ${this.manager}`;
});
}
};
console.log(department3.summary());



