JavaScript-da OOP-da Kontekstni Yo'qotish
Klasslar bilan ishlashda kontekst
yo'qolishi mumkin va this
klass ob'ektiga emas, boshqa narsaga
isora qiladi.
Keling, bu qanday sodir bo'lishi
va nima qilish kerakligini ko'rib chiqaylik.
Faraz qilaylik, bizda User
klassi bor, u foydalanuvchi nomi
va ushbu foydalanuvchi bo'lgan
shaharlar massivini o'z ichiga oladi:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Faraz qilaylik, shaharlarni chiqaradigan usul mavjud:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Faraz qilaylik, ushbu usulda biz klassning ba'zi yordamchi usulidan foydalanishga qaror qildik. Bunda kontekst yo'qoladi:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // kontekst yo'qoldi
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Muammoni, masalan, o'q funktsiyasini kiritish orqali tuzatish mumkin:
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);
}
}
Quyidagi kodda qilingan xatoni tuzating:
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);