Страта кантэксту ў ААП у JavaScript

Пры працы з класамі можа губляцца кантэкст і this будзе паказваць не на аб'ект класа, а на нешта іншае. Давайце паглядзім як гэта можа здарыцца і што з гэтым рабіць.

Хай у нас ёсць клас User, які змяшчае імя карыстальніка і масіў гарадоў, у якіх гэты карыстальнік быў:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
}

Хай ёсць метад, які выводзіць гарады:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
  
  showCities() {
    this.cities.forEach(function(city) {
      console.log(city);
    });
  }
}

Хай у гэтым метадзе мы вырашылі выкарыстоўваць некаторы дапаможны метад класа. У гэтым выпадку кантэкст і згубіцца:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
  
  showCities() {
    this.cities.forEach(function(city) {
      console.log(this.#cape(city)); // кантэкст страчаны
    });
  }
  
  #cape(str) {
    return str[0].toUpperCase() + str.slice(1);
  }
}

Можна выправіць праблему, напрыклад, увёўшы стрэлачную функцыю:

javascriptclass 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);
  }
}
Задание 1

Выправіце памылку, дапушчаную ў наступным кодзе:

javascriptclass 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);