การสูญเสีย context ใน OOP ใน JavaScript
เมื่อทำงานกับคลาส context อาจสูญหายได้
และ this จะไม่ได้ชี้ไปที่อ็อบเจกต์ของคลาส
แต่ชี้ไปที่อย่างอื่นแทน
มาดูกันว่ามันเกิดขึ้นได้อย่างไร
และจะจัดการกับมันอย่างไร
สมมติว่าเรามีคลาส User
ซึ่งเก็บชื่อผู้ใช้และอาร์เรย์
ของเมืองที่ผู้ใช้คนนี้
เคยไป:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
สมมติว่ามีเมธอดที่แสดง เมือง:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
สมมติว่าในเมธอดนี้เราตัดสินใจใช้ เมธอดตัวช่วยบางตัวของคลาส ในกรณีนี้ context จะสูญหาย:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // context สูญหายแล้ว
});
}
#cape(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
เราสามารถแก้ไขปัญหาได้ เช่น โดยใช้ฟังก์ชันลูกศร:
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);
}
}
แก้ไขข้อผิดพลาดที่เกิดขึ้น ในโค้ดต่อไปนี้:
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);