JavaScript-də OOP-də Kontekst İtirilməsi
Siniflərlə işləyərkən kontekst itirilə bilər
və this sinif obyektini deyil,
başqa bir şeyə işarə edəcək.
Gəlin görək bu necə baş verə bilər
və bununla nə etmək lazımdır.
Tutaq ki, bizim istifadəçi adını və şəhərlərin
massivini özündə saxlayan User sinfimiz var,
hansı ki, bu istifadəçi olub:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Tutaq ki, şəhərləri çıxaran metod var:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Tutaq ki, bu metodda biz sinfin müəyyən köməkçi metodundan istifadə etmək qərarına gəldik. Bu halda kontekst itiriləcək:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // kontekst itirildi
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Problemi, məsələn, ox funksiyası təqdim etməklə düzəltmək olar:
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);
}
}
Aşağıdakı kodda edilən səhvi düzəldin:
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);