JavaScript-dä OOP-de konteksti ýitirmek
Klaslar bilen işleýän wagtyňyzda kontekst ýitip biler we
this klasyň objekdine däl, başga bir zada görkezip biler.
Bunyň nädip ýüze çykyşyny we onuň bilen nämä etmeli bolşyny göreliň.
Bizde User atly bir klas bolsun, ol ulanyjynyň adyny we
şol ulanyjynyň bolan şäherleriniň sanawyny saklaýar:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Şäherleri çap edýän bir metoduňyz bolsun:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Bu metoduň içinde biz klasyň kömekçi metoduny ulanmak islesek. Şonda kontekst ýitip gider:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // kontekst ýitdi
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Mesele, meselem, ok şekilli funksiýa girizmek bilen düzeldip bolýar:
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şakdaky koda ýüze çykan ýalňyşlygy düzediň:
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);