JavaScript да ООП да контекст йўқолиши
Синфлар билан ишлашда контекст
йўқолиши мумкин, ва this
синф объектига эмас, бошқа нарсага
ишора қилади.
Келинг, бу қандай sodir бўлиши мумкинлигини
ва бу билан нима қилиш кераклигини кўриб чиқайлик.
Бизда 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);