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:
javascriptclass User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Şäherleri çap edýän bir metoduňyz bolsun:
javascriptclass 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:
javascriptclass 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:
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
Aşakdaky koda ýüze çykan ýalňyşlygy düzediň:
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);