JavaScriptにおけるオブジェクト指向プログラミングでのコンテキストの喪失
クラスを扱う際に、コンテキストが失われ、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);
});
}
}
このメソッド内でクラスの何らかのヘルパーメソッドを使うことにした場合、コンテキストは失われます。
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(this.#cape(city)); // コンテキストが失われた
});
}
#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);