კონტექსტის დაკარგვა OOP-ში 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);