Gubitak konteksta u OOP u JavaScript-u
Prilikom rada sa klasama kontekst se može izgubiti
i this će pokazivati
ne na objekat klase, već na nešto drugo.
Hajde da pogledamo kako se to može desiti
i šta da radimo po tom pitanju.
Neka imamo klasu User,
koja sadrži ime korisnika i niz
gradova u kojima je ovaj korisnik
bio:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Neka postoji metod koji ispisuje gradove:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Pretpostavimo da u ovom metodu odlučimo da koristimo neki pomoćni metod klase. U ovom slučaju će se kontekst izgubiti:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // kontekst je izgubljen
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Problem se može popraviti, na primer, uvodeći streličastu funkciju:
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);
}
}
Ispravite grešku koja je napravljena u sledećem kodu:
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);