JSFiddle - React, Tailwind, and code Playground
by LyndseyB
JavaScript
class Employees {
constructor() {
this._employeeList = [
{ name: 'Lyndsey Browning', age: 30 },
{ name: 'John Griffiths', age: 21 },
{ name: 'Jane Eaves', age: 45 }
];
this._names = [];
this._ages = [];
}
getNames() {
this._employeeList.forEach(function(employee) {
this._ages.push(employee.age); // _this is undefined because we're in a new scope created by the forEach method
});
this._employeeList.forEach((employee) => {
this._ages.push(employee.age); // _this is fine because arrow function creates lexical scope, therefore _this is still Employees!
});
return this._ages;
}
}
const employees = new Employees();
const names = employees.getNames();
console.log(names);