Контексти гумшуда дар ООП дар 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);