Humbja e Kontekstit në OOP në JavaScript

Gjatë punës me klasa, konteksti mund të humbasë dhe this do të tregojë jo te objekti i klasës, por diçka tjetër. Le të shohim se si mund të ndodhë kjo dhe çfarë të bëjmë me të.

Le të themi se kemi një klasë User, që përmban emrin e përdoruesit dhe një array të qyteteve ku ky përdorues ka qenë:

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

Le të themi se ekziston një metodë që nxjerr qytetet:

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

Le të themi se në këtë metodë kemi vendosur të përdorim disa metoda ndihmëse të klasës. Në këtë rast, konteksti do të humbasë:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
  
  showCities() {
    this.cities.forEach(function(city) {
      console.log(this.#cape(city)); // konteksti u humb
    });
  }
  
  #cape(str) {
    return str[0].toUpperCase() + str.slice(1);
  }
}

Problemi mund të korrigjohet, për shembull, duke futur një funksion shigjete:

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

Korrigjoni gabimin e bërë në kodin e mëposhtëm:

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