Losing Context in OOP in JavaScript
When working with classes, context can be lost and this will point not to the class object, but to something else. Let's see how this can happen and what to do about it.
Let's say we have a class User, which contains the user name and an array of cities where this user was:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Let there be a method that outputs cities:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Let's say we decide to use some helper class method in this method. In this case, the context will be lost:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // the context is lost
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
You can fix the problem, for example, by introducing an arrow function:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(city => {
console.log(this.#cape(city));
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Please correct the error in the following code:
class Employee {
constructor(name, salary, coeffs) {
this.name = name;
this.salary = salary;
this.coeffs = coeffs;
}
getTotal() {
return this.coeffs.reduce(function(res, coeff) {
return res + this.salary * coeff;
}, 0);
}
}
let employee = new Employee('john', 1000, [1.1, 1.2, 1.3]);
let total = employee.getTotal();
console.log(total);