Կոնտեքստի կորուստ OOP-ում 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);