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