JavaScript'te OOP'de Bağlam Kaybı
Sınıflarla çalışırken bağlam kaybolabilir
ve this, sınıfın nesnesini değil de
başka bir şeyi gösterebilir.
Bunun nasıl olabileceğine ve bu konuda
ne yapılacağına bir bakalım.
Bir User sınıfımız olduğunu varsayalım,
bu sınıf kullanıcının adını ve bu kullanıcının
bulunduğu şehirlerin bir dizisini içerir:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
Şehirleri gösteren bir metod olduğunu varsayalım:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
Diyelim ki bu metodun içinde sınıfın bazı yardımcı metodlarını kullanmaya karar verdik. Bu durumda bağlam kaybolacaktır:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // bağlam kayboldu
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Sorun, örneğin bir ok fonksiyonu tanımlayarak düzeltilebilir:
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ğıdaki kodda yapılan hatayı düzeltin:
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);