Here is my code:
class Employee {
constructor(ename) {
this.ename = ename;
}
}
class EmployeeRenderer {
constructor(employees) {
this.employees = employees;
this.ename = "EmployeeRenderer";
}
renderWithArrowFunc() {
this.employees.forEach(emp => {
console.log(this.ename); // Will print EmployeeRenderer 3 times
})
}
}
var employees = [
new Employee('Alex'),
new Employee('Bob'),
new Employee('Smith')
];
var employeeRenderer = new EmployeeRenderer(employees);
employeeRenderer.renderWithArrowFunc();
As we know, in an arrow function, this
is not a declared variable, so to resolve a reference to this
, JavaScript consults with the enclosing scope(s). As such, in the above code, when console.log(this.ename)
is being executed, JavaScript asks the first immediate enclosing lexical scope- the function forEach
- about this
. In forEach
implementation** , this
points at the value of the array on which the function has been called: employees
and as it doesn't have ename
property, so I expected to see undefined
3 times in the output than EmployeeRenderer
. It shows that this
has been resolved to EmployeeRenderer.ename
. What am I missing here?
** I searched for an implementation of forEach
and couldn't find one, hence I assume it must be identical to the pollyfill mentioned in MDN.