Губитак контекста у ООП-у у 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);