კონტექსტის დაკარგვა OOP-ში JavaScript-ში
კლასებთან მუშაობისას შეიძლება დაიკარგოს
კონტექსტი და this აღარ
მიუთითებს კლასის ობიექტზე, არამედ სხვა რამეზე.
ვნახოთ, როგორ შეიძლება მოხდეს ეს
და რა ვუყოთ ამას.
დავუშვათ, გვაქვს კლასი User,
რომელიც შეიცავს მომხმარებლის სახელს და ქალაქების მასივს,
რომელშიც ეს მომხმარებელი
იმყოფებოდა:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
დავუშვათ, არის მეთოდი, რომელიც გამოსახავს ქალაქებს:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
დავუშვათ, ამ მეთოდში გადავწყვიტეთ გამოვიყენოთ კლასის რაიმე დამხმარე მეთოდი. ამ შემთხვევაში კონტექსტი დაიკარგება:
class 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);
}
}
პრობლემის მოგვარება შესაძლებელია, მაგალითად, ისრის ფუნქციის გამოყენებით:
class 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);
}
}
გამასწორეთ შეცდომა, რომელიც დაშვებულია შემდეგ კოდში:
class 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);