Izguba konteksta v OOP v JavaScript
Pri delu z razredi lahko pride do izgube
konteksta in this bo kazal
ne na objekt razreda, ampak na kaj drugega.
Poglejmo, kako se to lahko zgodi
in kaj storiti glede tega.
Recimo, da imamo razred User,
ki vsebuje ime uporabnika in seznam
mest, v katerih je bil ta uporabnik:
javascriptclass User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Recimo, da obstaja metoda, ki izpiše mesta:
javascriptclass User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Recimo, da smo v tej metodi odločili uporabiti neko pomožno metodo razreda. V tem primeru se bo kontekst izgubil:
javascriptclass User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // kontekst se je izgubil
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Težavo je mogoče popraviti, na primer, z uvedbo puščične funkcije:
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
Popravite napako, storjeno v naslednji kodi:
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);