Strata kontextu v OOP v JavaScript
Pri práci s triedami môže dôjsť k strate
kontextu a this bude ukazovať
nie na objekt triedy, ale na niečo iné.
Pozrime sa, ako sa to môže stať
a čo s tým robiť.
Nech máme triedu User,
ktorá obsahuje meno užívateľa a pole
miest, v ktorých tento užívateľ
bol:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Nech existuje metóda, ktorá vypisuje mestá:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Nech v tejto metóde sme sa rozhodli použiť nejakú pomocnú metódu triedy. V tomto prípade sa kontext stratí:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // kontext sa stratil
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Problém môžeme opraviť, napríklad zavedením šípkovej funkcie:
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);
}
}
Opravte chybu, ktorá bola urobená v nasledujúcom kóde:
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);